android 相机预览保存图片

记录之前没太注意的细节问题。

之前相机拍照保存图片都是用的提供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();
}
}

posted @ 2020-07-07 17:51  #Skye  阅读(1331)  评论(3)    收藏  举报