Reputation: 124
I've built a camera app which let me take pictures but I want to save it with a specific (preset) width/height and aspect ratio.
Example:
I've tried the following (without luck):
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(editPhotoFile.getAbsolutePath(), bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
Bitmap croppedBmp = Bitmap.createBitmap(bitmap, margin, margin, bitmap.getWidth() - margin, bitmap.getHeight() - margin);
With the margins I've tried to accomplish to cut a specific amount of pixels on the left (first margin) and top (second margin) and the same on the total width and height. Not working.
There are also some libraries on Github available, but they all let me select an image and edit it - I don't need the manual editing, I want to have preset margins to crop.
Also, the possible solutions here on Stack Overflow and just by Googling or finding tutorials don't give me any luck. Search queries:
java android crop image
java android crop image tutorial
Who can help me?
Upvotes: 1
Views: 2004
Reputation: 124
I'm getting there as well. Struggled for weeks, but my brain got clearified: everything was doing OK, but I wasn't saving the picture/image to the device.
Margins are working.
Will update/edit this post tomorrow with the solution I've found.
Update:
// get String with path to file from other activity and make new File of it
File editPhotoFile = new File(globalFileString);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);
// crop the bitmap with new margins: bitmap, left, top, width, height
Bitmap croppedBmp = Bitmap.createBitmap(bitmap, marginLeft, marginTop, bitmapHeight, bitmapWidth);
// save bitmap to new file
FileOutputStream out = null;
File mediaFile;
try {
mediaFile = new File(globalFileString);
out = new FileOutputStream(mediaFile);
croppedBmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 1