How to rotate an image and save it without re compressing it? - android

I have an Image File (jpg) and i need to rotate it. However, i would like to avoid to re compress it when saving it back to the disk. Is their any way to do this?
I save the image like this:
matrix.setRotate(-90);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
FileOutputStream fileoutputstream = new FileOutputStream(imagePath);
bmRotated.compress(CompressFormat.JPEG, 100, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
bmRotated.recycle();

Maybe you can try to extract the data from your bitmap to a byte array and save that array. (Code not tested, maybe it does not work).
Bitmap bitmap = new Bitmap()...
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byte[] byteArray = byteBuffer.array();
FileOutputStream output = new FileOutputStream("filename");
output.write(byteArray);
output.close();

Use PNG instead of JPG. PNG format is loseless data format with compress.
https://en.wikipedia.org/wiki/Portable_Network_Graphics
matrix.setRotate(-90);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
FileOutputStream fileoutputstream = new FileOutputStream(imagePath);
bmRotated.compress(CompressFormat.PNG, 100, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
bmRotated.recycle();
Or, you can use Compressor library, to use WEBP format.
WEBP supports both lossless and loss. https://en.wikipedia.org/wiki/WebP
https://github.com/zetbaitsu/Compressor
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(100)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(actualImage);

Related

How to convert YUV_420_888 image to bitmap [duplicate]

This question already has answers here:
Android Camera2 API YUV_420_888 to JPEG
(3 answers)
Closed 4 years ago.
I am working on AR project where i need to capture the current frame and save it to gallery. I am able to get the image using Frame class in AR core , but the format of image is YUV_420_888. I have already tried lots of solutions to covert this to bitmap but couldn't able to solve it.
This is how I convert to jpeg.
public Bitmap imageToBitmap(Image image, float rotationDegrees) {
assert (image.getFormat() == ImageFormat.NV21);
// NV21 is a plane of 8 bit Y values followed by interleaved Cb Cr
ByteBuffer ib = ByteBuffer.allocate(image.getHeight() * image.getWidth() * 2);
ByteBuffer y = image.getPlanes()[0].getBuffer();
ByteBuffer cr = image.getPlanes()[1].getBuffer();
ByteBuffer cb = image.getPlanes()[2].getBuffer();
ib.put(y);
ib.put(cb);
ib.put(cr);
YuvImage yuvImage = new YuvImage(ib.array(),
ImageFormat.NV21, image.getWidth(), image.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0,
image.getWidth(), image.getHeight()), 50, out);
byte[] imageBytes = out.toByteArray();
Bitmap bm = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
Bitmap bitmap = bm;
// On android the camera rotation and the screen rotation
// are off by 90 degrees, so if you are capturing an image
// in "portrait" orientation, you'll need to rotate the image.
if (rotationDegrees != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegrees);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm,
bm.getWidth(), bm.getHeight(), true);
bitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
}
return bitmap;
}

Android scaling copy of image instead of changing source image

I have the following code for getting small sized avatar image:
Bitmap b= BitmapFactory.decodeFile(selectedImagePath);
File file = new File(selectedImagePath);
Bitmap out = Bitmap.createScaledBitmap(b, 128, 128, false);
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
}
The problem is that after executing this code, my image in gallery is rescaled too, but I must leave it without any changes.
I tried to use copy of Bitmap image like this:
Bitmap bmp2 = b.copy(b.getConfig(), true);
Bitmap out = Bitmap.createScaledBitmap(bpm2, 128, 128, false);
or
Bitmap bmp2 = Bitmap.createBitmap(b);
Bitmap out = Bitmap.createScaledBitmap(bpm2, 128, 128, false
But my original image still changes. How could I obtain new, independent copy of this image?
You are loading the image from "selectedImagePath" and then your output file points to the same path, when you call compress() you overwrite your original image.
Try making a new name for the resized image.
fOut = new FileOutputStream(renamedFile);

Rotate byte array of JPEG after onPictureTaken

Is there a way to rotate byte array without decoding it to Bitmap?
Currently in jpeg PictureCallback I just write byte array directly to file. But pictures are rotated. I would like to rotate them without decoding to bitmap with hope that this will conserve my memory.
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, o);
int orientation;
if (o.outHeight < o.outWidth) {
orientation = 90;
} else {
orientation = 0;
}
File photo = new File(tmp, "demo.jpeg");
FileOutputStream fos;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(photo);
bos = new BufferedOutputStream(fos);
bos.write(data);
bos.flush();
} catch (IOException e) {
Log.e(TAG, "Failed to save photo", e);
} finally {
IOUtils.closeQuietly(bos);
}
Try this. It will solve the purpose.
Bitmap storedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, null);
Matrix mat = new Matrix();
mat.postRotate("angle"); // angle is the desired angle you wish to rotate
storedBitmap = Bitmap.createBitmap(storedBitmap, 0, 0, storedBitmap.getWidth(), storedBitmap.getHeight(), mat, true);
You can set JPEG rotation via Exif header without decoding it. This is the most efficient method, but some viewers may still show a rotated image.
Alternatively, you can use JPEG lossless rotation. Unfortunately, I am not aware of free Java implementations of this algorithm.
Update on SourceForge, there is a Java open source class LLJTran. The Android port is on GitHub.
I don't think that there is such possibility. Bytes order depends from picture encoding (png, jpeg). So you are forced to decode image to do something with it.
Try like this,
private byte[] rotateImage(byte[] data, int angle) {
Log.d("labot_log_info","CameraActivity: Inside rotateImage");
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, null);
Matrix mat = new Matrix();
mat.postRotate(angle);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
You can call the rotateImage by providing the image data which is getting from onPictureTaken method and an angle for rotation.
Eg: rotateImage(data, 90);

Out Of memory Error while sending the large bitmap to server

My question might be old but I am suffering because of this issue from last 2 weeks and now its too much, in my application I need to send large image bitmap to server and I am doing this by below coding:
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
File file=new File(TabGroupActivity.path);
FileInputStream input=null;
try {
input = new FileInputStream(TabGroupActivity.path);
} catch (FileNotFoundException e) {
//TODO do something intelligent
e.printStackTrace();
}
if(input!=null)
{
bitmap = BitmapFactory.decodeStream(input, null, bfOptions);
}
Matrix mat = new Matrix();//removing rotations
if(TabGroupActivity.rotation==90 || TabGroupActivity.rotation==270)
{
mat.setRotate(90);
}
else if(TabGroupActivity.rotation==0 || TabGroupActivity.rotation==180)
{
mat.setRotate(0);
}
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int height= bitmap.getHeight();
int width=bitmap.getWidth();
{
//formula for calculating aspect ratio
float k= (float) height/width;
newHeight =Math.round(620*k);
}
byte[] buffer=new byte[10];
while(input.read(buffer)!=-1)
{
bos.write(buffer);
}
bitmap = Bitmap.createScaledBitmap(bitmap , 620, newHeight, true);
bitmap.compress(CompressFormat.JPEG, 90, bos);
byte[] imageData = bos.toByteArray();
ContentBody cb = new ByteArrayBody(imageData, "image/jpg", "image1.jpeg");
input.close();
but after sending 2,3 images I am getting out of memory error on BitmapFactory.decodeStream() please help me the resolve this issue the main thing I can not re-size or crop image, I need to send good quality image only to server.
Recycle your bitmaps every time you are done with them by calling bitmap.recycle(), this should help a bit. Also optimize your code a bit; this part:
if(TabGroupActivity.rotation==90 || TabGroupActivity.rotation==270)
{
mat.setRotate(90);
}
else if(TabGroupActivity.rotation==0 || TabGroupActivity.rotation==180)
{
mat.setRotate(0);
}
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
You can reduce to
if(TabGroupActivity.rotation==90 || TabGroupActivity.rotation==270)
{
mat.setRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
}
So you don't have to create a new bitmap in every case.
Also, you can experiment with the BitmapFactory.Options.inSampleSize to get smaller images.

Android: How can I save image files that are not (JPEG & PNG)? [after rotate]

I am trying to rotate an image from sdcard and then save back to sdcard.
I can do that for ".jpg" format by using ExifInterface class:
exif = new ExifInterface(filepath);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, Integer.toString(orientation));
exif.saveAttributes();
For ".png" files, I would have to actually rotate and save:
Bitmap bitmap = BitmapFactory.decodeFile(filepath);
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
FileOutputStream stream = new FileOutputStream(fileLocation);
bitmap.compress(CompressFormat.PNG, 100, stream);
What about ".bmp", ".tiff", ".gif" ??
It seems like CompressFormat only supports 'CompressFormat.PNG' and 'CompressFormat.JPG'.
Is this limitation?
Yes Limited To JPG , PNG , WEBP
http://developer.android.com/reference/android/graphics/Bitmap.CompressFormat.html
Hey just give the name to .bmp
Do this:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "**test.bmp**")
it'll sound that IM JUST FOOLING AROUND but try it once it'll get saved in bmp foramt..Cheers

Categories

Resources