Bitmap originalBitmap = BitmapFactory.decodeFile("/path/to/image.jpg"); OutputStream outputStream = new FileOutputStream("/path/to/compressed/image.jpg"); originalBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); originalBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); byte[] compressedData = outputStream.toByteArray();In this example, we load an original bitmap image from a resource using BitmapFactory.decodeResource. We then create a ByteArrayOutputStream to write the compressed image data to a byte array. Finally, we call compress on the original bitmap with a PNG compression format, a quality level of 100%, and the ByteArrayOutputStream we just created. We then convert this stream to a byte array for further use. This method belongs to the android.graphics package library.