記錄之前沒太注意的細節問題。
之前相機拍照保存圖片都是用的提供onPictureCallback這個回調,很想當然的沒考慮過什么格式啊,
這次需要從預覽數組中保存圖片才意識不只是把byte[]直接寫文件保存下來,保存的圖片無法查看;
在攝像頭預覽的時候,我們可以通過實現接口PreviewCallback方法可以得到每幀的視頻數據,
但獲取的數據不能直接將數據保存為Bitmap,因為該預覽幀數據使用android默認的NV21格式,
NV21格式其實是一種YUV格式,需要進行轉換為最常見的就是rgb和jpeg類型;
public Bitmap bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
public Bitmap decodeToBitMap(byte[] data, Camera camera) {
try {
//格式成YUV格式
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, camera.getParameters().getPreviewSize().width,
camera.getParameters().getPreviewSize().height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, camera.getParameters().getPreviewSize().width,
camera.getParameters().getPreviewSize().height), 100, baos);
Bitmap bitmap = bytes2Bimap(baos.toByteArray());
saveImage(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void saveImage(Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), "HDPicture");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}