我正在编写一个 Android 应用程序,当用户点击一个按钮时,它会保存来自相机的 JPEG 快照。不幸的是,当我查看 JPEG 文件时,我的代码正在保存看起来已损坏。这似乎是由我调用 parameters.setPreviewSize 引起的(请参阅下面的代码 fragment )-如果我删除它,则图像保存良好;但是,如果没有它,我将无法设置预览大小,而且如果没有它,setDisplayOrientation 似乎也没有任何效果。
我的应用程序以 API 级别 8 (Android 2.2) 为目标,我正在 HTC Desire HD 上进行调试。不太确定我在这里做错了什么......非常感谢任何帮助!
干杯, 斯科蒂
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size size = getBestPreviewSize(w,h);
// This next call is required in order for preview size to be set and
// setDisplayOrientation to take effect...
// Unfortunately it's also causing JPEG to be created wrong
parameters.setPreviewSize(size.width, size.height);
parameters.setPictureFormat(ImageFormat.JPEG);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
}
// This is the snapshot button event handler
public void onSnapshotButtonClick(View target) {
//void android.hardware.Camera.takePicture(ShutterCallback shutter,
// PictureCallback raw, PictureCallback jpeg)
mPreview.mCamera.takePicture(null, null, mPictureCallback);
}
// This saves the camera snapshot as a JPEG file on the SD card
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
if (imageData != null) {
FileOutputStream outStream = null;
try {
String myJpgPath = String.format(
"/sdcard/%d.jpg", System.currentTimeMillis());
outStream = new FileOutputStream(myJpgPath);
outStream.write(imageData);
outStream.close();
Log.d("TestApp", "onPictureTaken - wrote bytes: "
+ imageData.length);
c.startPreview();
Toast.makeText(getApplicationContext(), String.format("%s written", myJpgPath), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
};
最佳答案
另一种解决方法是匹配预览和图片尺寸之间的纵横比(即 setPreviewSize(w1,h1); setPictureSize(w2,h2) 与 w1/h1 ~ w2/h2(小的差异似乎没问题))。例如。对于 Desire HD S w1=800,h1=480, w2=2592,h2=1552 和 w1=960,h1=720,h2=2592,h2=1952 一样有效(如果您不介 Intent 像失真的话 ;-)
关于Android:从相机保存的 Jpeg 看起来已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5859876/