我需要将文件从文件加载到ImageView上,然后将其保存到同一个文件中。所有的修改都是在称为mCanvasView
的单独视图中绘制的。这是我的保存代码:
private void saveResult() {
OutputStream stream = null;
try {
Bitmap result;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
result = BitmapFactory.decodeFile(mFilePath, options);
} else {
Bitmap bitmap = BitmapFactory.decodeFile(mFilePath);
result = bitmap.copy(Bitmap.Config.ARGB_8888, true);
bitmap.recycle();
}
float resultWidth = result.getWidth();
float resultHeight = result.getHeight();
Canvas canvas = new Canvas(result);
Bitmap overlay = mCanvasView.getDrawingCache();
Matrix matrix = new Matrix();
matrix.setScale(resultWidth / overlay.getWidth(), resultHeight
/ overlay.getHeight());
canvas.drawBitmap(overlay, matrix, new Paint());
stream = new FileOutputStream(mFilePath);
result.compress(CompressFormat.PNG, 100, stream);
} catch (Exception e) {
e.printStackTrace();
leaveActivityWithMissingData();
} finally {
IOUtils.closeQuietly(stream);
}
}
首先 - 它真的很慢。我不明白为什么。其次,如果以纵向模式拍摄的图像,则保存的图像将被旋转。为什么?我不申请任何轮换。
我已经修改了这样的代码,以便使用来自EXIF的旋转数据:
OutputStream stream = null;
try {
Bitmap original;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
original = BitmapFactory.decodeFile(mFilePath, options);
} else {
Bitmap bitmap = BitmapFactory.decodeFile(mFilePath);
original = bitmap.copy(Bitmap.Config.ARGB_8888, true);
bitmap.recycle();
}
int resultWidth = original.getWidth();
int resultHeight = original.getHeight();
int rotation = Utils.getRotation(mFilePath);
if (rotation % 180 != 0) {
resultHeight = original.getWidth();
resultWidth = original.getHeight();
}
Bitmap result = Bitmap.createBitmap(resultWidth, resultHeight,
Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Matrix rotationMatrix = new Matrix();
rotationMatrix.setRotate(rotation, resultWidth / 2,
resultHeight / 2);
canvas.drawBitmap(original, rotationMatrix, new Paint());
original.recycle();
Bitmap overlay = mCanvasView.getDrawingCache();
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(resultWidth / overlay.getWidth(), resultHeight
/ overlay.getHeight());
canvas.drawBitmap(overlay, scaleMatrix, new Paint());
overlay.recycle();
stream = new FileOutputStream(mFilePath);
result.compress(CompressFormat.PNG, 100, stream);
result.recycle();
} catch (Exception e) {
e.printStackTrace();
leaveActivityWithMissingData();
} finally {
IOUtils.closeQuietly(stream);
}
但是每次通话都会导致OOM。我究竟做错了什么?
答案 0 :(得分:0)
检查this可能有助于了解性能问题。
此外,请勿忘记在完成压缩后关闭stream
。
至于旋转 - 可能是您的相机设置了setDisplayOrientation(90)
或类似的原始预览模式?然后,您可以通过应用matrix.postRotate(90);