thomasp
thomasp

Reputation: 31

Android: image saved using copyPixelsFromBuffer is distorted

I am trying to make an image processing program in Android Studio and I have a problem concerning how to save a Bitmap.

My problem is about saving an image which comes from a ByteBuffer.

To show it here, I have done this: I load an image in a ByteBuffer and I try to save it, rescaled to 1014x1163 pixels. And the image I get is distorted, messy.

For example, here is an image I load:

enter image description here

And here is what I get in the image I save:

enter image description here

Here is my code:

imageSize = (int) (bmWidth*bmHeight*4);
ByteBuffer pixelsArray = ByteBuffer.allocateDirect(imageSize);
ByteBuffer outputArray = ByteBuffer.allocateDirect(imageSize);

workingBitmap.copyPixelsToBuffer(pixelsArray);
workingBitmap.copyPixelsToBuffer(outputArray);

int thiswidth   = workingBitmap.getWidth();
int thisheight  = workingBitmap.getHeight();

Bitmap copiedBitmap = Bitmap.createScaledBitmap(workingBitmap, Width, Height, false);

int thiswidth2   = copiedBitmap.getWidth();
int thisheight2  = copiedBitmap.getHeight();

outputArray.rewind();
copiedBitmap.copyPixelsFromBuffer(outputArray);
SaveJPG(copiedBitmap);

The function SaveJPG works fine because if I call SaveJPG(workingBitmap) it saves a normal image.

Here is the code with variables values during debugging:

enter image description here

I am wondering if the problem comes from the fact that the output resolution is not a multiple of 4. That's mandatory in my program: the output image resolution can be of any value (odd or even).

I have tried many different things (copying workingBitmap and resizing the copy for example).

No success. I don't know what the cause of the problem is.

Does anyone have some source code which can save an image of any resolution, stored in a ByteBuffer ?

Thanks in advance.

Upvotes: 1

Views: 315

Answers (2)

thomasp
thomasp

Reputation: 31

I have found the cause of the problem. It was simply due to a problem in the width and height of the input image: I was using the width and height of the View which displays the input bitmap, instead of using the bitmap's width and height.

Upvotes: 0

Sambhav Khandelwal
Sambhav Khandelwal

Reputation: 3765

Try this

try (FileOutputStream out = new FileOutputStream(yourFileName)) {
    yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
    e.printStackTrace();
}

Or use this

MediaStore.Images.Media.insertImage(getContentResolver(), yourbitmap,
    "File name", "description of the image");

Upvotes: 1

Related Questions