操作相機(jī)的Preview可通過(guò)以下三種方式添加回調(diào)接口:
Camera.setPreviewCallbackBuffer(PreviewCallback)
Camera.setOneShotPreviewCallback(PreviewCallback)
Camera.setPreviewCallback(PreviewCallback)
PreviewCallback接口里面只有一個(gè)回調(diào)方法:
void onPreviewFrame(byte[] data, Camera camera);
一、生成Bitmap –> 旋轉(zhuǎn)Bitmap
其中的byte[] data就是Preview的圖像數(shù)據(jù),格式為YuvImage,而這個(gè)圖像天生是橫著的篓像,一般的旋轉(zhuǎn)操作是:
YuvImage的byte[] –> Bitmap的byte[] –> 生成Bitmap –> 旋轉(zhuǎn)Bitmap
public void onPreviewFrame(byte[] data, Camera camera) {
final int width = camera.getParameters().getPreviewSize().width;
final int height = camera.getParameters().getPreviewSize().height;
// 通過(guò)YuvImage得到Bitmap格式的byte[]
YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 100, out);
byte[] dataBmp = out.toByteArray();
// 生成Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, dataBmp.length);
// 旋轉(zhuǎn)
Matrix matrix = new Matrix();
matrix.setRotate(90);
Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
// 保存到本地
File file = new File("/storage/emulated/0/" + System.currentTimeMillis() + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
}
二、可以直接旋轉(zhuǎn)YuvImage。
原理 很復(fù)雜 直接上工具類(lèi)
public void onPreviewFrame(final byte[] data, Camera camera) {
// 將系統(tǒng)回調(diào)的數(shù)組拷貝一份,操作拷貝的數(shù)據(jù)
byte[] dataCopy = new byte[data.length];
System.arraycopy(srcData, 0, dataCopy , 0, data.length);
Camera.Size size = camera.getParameters().getPreviewSize();
final int srcWidth = size.width;
final int srcHeight = size.height;
final int dstWidth = size.height;
final int dstHeight = size.width;
// 1.5倍的總數(shù),多出來(lái)的部分裝VU分量
byte[] buf = new byte[dstWidth * dstHeight * 3 / 2];
for (int i = 0; i < dstHeight; i++) {
for (int j = 0; j < dstWidth; j++) {
// 新數(shù)組中擺放Y值 旋轉(zhuǎn)后(i,j) --> 旋轉(zhuǎn)前(srcHeight-1-j, i)
buf[i * dstWidth + j] = dataCopy[(srcHeight - 1 - j) * srcWidth + i];
// 確認(rèn)是左上角的點(diǎn)
if (i % 2 == 0 && j % 2 == 0) {
// 擺放V值 目標(biāo)行號(hào)= 行號(hào)/2 + 高
buf[(i / 2 + srcWidth) * dstWidth + j] = dataCopy[((srcHeight - 1 - j) / 2 + srcHeight) * srcWidth + j];
// 擺放U值
buf[(i / 2 + srcWidth) * dstWidth + j + 1] = dataCopy[((srcHeight - 1 - j) / 2 + srcHeight) * srcWidth + j + 1];
}
}
}
YuvImage yuvImage = new YuvImage(buf, ImageFormat.NV21, dstWidth, dstHeight, null);
File file = new File("/storage/emulated/0/" + System.currentTimeMillis() + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
yuvImage.compressToJpeg(new Rect(0, 0, dstWidth, dstHeight), 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
}