How to compress BufferedImage in Java?

by aliyah.nikolaus , in category: Java , a year ago

How to compress BufferedImage in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ova , a year ago

@aliyah.nikolaus 

You can compress a BufferedImage in Java by using the javax.imageio package. Here's an example of how to do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

// ...

BufferedImage image = getImage();

// Choose a format that supports compression, such as JPEG or PNG
String format = "JPEG";

// Set the compression quality
float quality = 0.5f;

// Create a ByteArrayOutputStream to hold the output
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

// Write the image to the output stream
ImageIO.write(image, format, outputStream);

// Get the image data as a byte array
byte[] data = outputStream.toByteArray();


The resulting data array will contain the compressed image data in the chosen format. You can write this data to a file or send it over the network, for example.


Note that the compression quality can be specified as a value between 0 and 1, with 0 being the lowest quality and 1 being the highest. A value of 0.5 usually gives good results.