1

I'm loading a jpeg-file via BitmapFactory and try to save it again (later I want to do some calculation on the pixel data before I save it again).

But if I try to save it with

FileOutputStream fos = new FileOutputStream(new File("/sdcard/test.jpg"));
originalImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);

then it is not exactly the same result as in the original picture. Some pixel have got different color values and this ist not useful for my later calculation.

Is there a possibility to safe it lossless? Or is the problem already when I load the picture with

Bitmap originalImage = BitmapFactory.decodeFile("/sdcard/input.jpg");

few lines before?

Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
Steve
  • 33
  • 1
  • 6

1 Answers1

5

Is there a possibility to safe it lossless?

No. The JPEG format uses a lossy compression. It makes no formal guarantees even if you set the quality to 100.

Or is the problem already when I load the picture with [...]

No, bitmaps are... maps of bits, i.e. they represent the exact bits of the image data.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Ok, but when I try it with Java in a usual Project, I would do it with `BufferedImage originalImage = ImageIO.read(new File("input.jpg")); ImageIO.write(originalImage , "jpg", new File("test.jpg"));` and this would work lossless. Sadly Android doesn't support ImageIO, but isn't there any way to do it like that? – Steve Feb 08 '12 at 15:18
  • 1
    Use a lossless compression like PNG if you don't want the pixel values to change – BitBank Feb 08 '12 at 15:22
  • There's unfortunately no guarantee that *x = compressJpeg(decompressJpeg(x))* holds for all *x*. (It *may* obviously be the case for some values of *x*, and some jpeg-algoritms, but you shouldn't rely on it.) As BitBank says, use PNG (or BMP) for lossless image storage. – aioobe Feb 08 '12 at 15:58
  • a lot more information and perhaps a workaround to android's lossy JPEG codec can be found here: https://stackoverflow.com/questions/36487971/how-to-compress-bitmap-as-jpeg-with-least-quality-loss-on-android – Itay Bianco Aug 17 '17 at 20:38