I need to load image from file to ImageView draw something on it and save to the same file. All of mine modifications are drawn in separate view called mCanvasView
. Here is my saving code:
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);
}
}
First of all - it's really slow. I don't understand why. Secondly, if image shot in portrait mode then saved image will be rotated. Why? I don't apply any rotation.
I've modified my code like this to use rotation data from 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);
}
But this leads to OOM on every call. What am I doing wrong?