我一直在扩充 QR 扫描库 Zxing,以便在扫描后立即保存照片。我被建议在 PreviewCallback.java 中的 onPreviewFrame 方法中这样做,如下所示:
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
Handler thePreviewHandler = previewHandler;
YuvImage im = new YuvImage(data, ImageFormat.NV21, 1200,
800, null);
Rect r = new Rect(0, 0, 1200, 800);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
im.compressToJpeg(r, 50, baos);
try {
FileOutputStream output = new FileOutputStream("/sdcard/test_jpg.jpg");
output.write(baos.toByteArray());
output.flush();
output.close();
System.out.println("Attempting to save file");
System.out.println(data);
} catch (FileNotFoundException e) {
System.out.println("Saving to file failed");
} catch (IOException e) {
System.out.println("Saving to file failed");
}
if (cameraResolution != null && thePreviewHandler != null) {
Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler or resolution available");
}}
运行此代码的结果是设置文件目录中的损坏图像。我相信这是由于每帧都运行代码。如果允许保存完整图像,是否有办法将其限制为每秒左右,或者是否有一种方法可以让图像仅在完成扫描后保存。
我有一个不太有利的工作选择,因为我可以成功保存扫描时显示的黑白图像;颜色当然是首选。
更新:代码更改为(理论上)适应任何设备上的相机分辨率。图像仍然损坏。
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
Handler thePreviewHandler = previewHandler;
android.hardware.Camera.Parameters parameters = camera.getParameters();
android.hardware.Camera.Size size = parameters.getPictureSize();
int height = size.height;
int width = size.width;
YuvImage im = new YuvImage(data, ImageFormat.NV21, width,
height, null);
Rect r = new Rect(0, 0, width, height);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
im.compressToJpeg(r, 50, baos);
try {
FileOutputStream output = new FileOutputStream("/sdcard/test_jpg.jpg");
output.write(baos.toByteArray());
output.flush();
output.close();
System.out.println("Attempting to save file");
System.out.println(data);
} catch (FileNotFoundException e) {
System.out.println("Saving to file failed");
} catch (IOException e) {
System.out.println("Saving to file failed");
}
if (cameraResolution != null && thePreviewHandler != null) {
Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler or resolution available");
}}
检查宽度和高度变量是否正确设置为 Nexus 7 的相机宽度和高度 1280x960。我相信问题来自于尝试保存每一帧图像,因为“尝试保存到文件”在 logcat 中出现的速度有点快;每秒几次。还可能值得注意的是,保存的损坏图像是方形的(ish)。
提前致谢。