How to save JPEG image on Android with custom quality level

On Android, how to save a JPEG image file with 30% quality?

In standard Java, I would use ImageIO to read the image as a BufferedImage , and then save it as a JPEG file using an IIOImage instance: http://www.universalwebservices.net/web-programming-resources/java/adjust-jpeg-image-compression -quality-when-saving-images-in-java . It seems, however, that Android does not have the javax.imageio package.

+7
source share
3 answers

You can save the bitmap image in JPEG format by calling compression and setting the second parameter:

 Bitmap bm2 = createBitmap(); OutputStream stream = new FileOutputStream("/sdcard/test.jpg"); /* Write bitmap to file using JPEG and 80% quality hint for JPEG. */ bm2.compress(CompressFormat.JPEG, 80, stream); 
+18
source
 InputStream in = new FileInputStream(file); try { Bitmap bitmap = BitmapFactory.decodeStream(in); File tmpFile = //...; try { OutputStream out = new FileOutputStream(tmpFile); try { if (bitmap.compress(CompressFormat.JPEG, 30, out)) { { File tmp = file; file = tmpFile; tmpFile = tmp; } tmpFile.delete(); } else { throw new Exception("Failed to save the image as a JPEG"); } } finally { out.close(); } } catch (Throwable t) { tmpFile.delete(); throw t; } } finally { in.close(); } 
+3
source

@Phyrum Tea is good just remember to close everything

 InputStream in = new FileInputStream(context.getFilesDir()+"image.jpg"); Bitmap bm2 = BitmapFactory.decodeStream(in); OutputStream stream = new FileOutputStream(String.valueOf(context.getFilesDir()+pathImage+"/"+idPicture+".jpg")); bm2.compress(Bitmap.CompressFormat.JPEG, 50, stream); stream.close(); in.close(); 
+1
source

All Articles