Avatar of Rohit Bajaj
Rohit Bajaj
Flag for India

asked on 

Compress a BufferedImage in java

How to reduce the size of a BufferedImage object in java.
I have constructed a bufferedImage merged from some images like this :
 public static BufferedImage mergeImages(List<PreSignedUrlResponse> preSignedUrlResponseList) {
    List<BufferedImage> imageList = new ArrayList<>();
    int width = 0;
    int maxHeight = 0;
    for (PreSignedUrlResponse preSignedUrlResponse : preSignedUrlResponseList) {
      try {
        BufferedImage image = ImageIO.read(new URL(preSignedUrlResponse.getPreSignedUrl()));
        width += image.getWidth();
        maxHeight = Math.max(image.getHeight(), maxHeight);
      } catch (Exception e) {

    BufferedImage merged = new BufferedImage(width, maxHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = (Graphics2D) merged.getGraphics();
    int currenWidth = 0;
    for (BufferedImage bufferedImage : imageList) {
      graphics2D.drawImage(bufferedImage, currenWidth, 0, null);
      currenWidth += bufferedImage.getWidth();
    return merged;

Open in new window

And i am creating an inputstream like this to upload it to an sftp server .:

private InputStream getInputStream(BufferedImage mergedImage) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
      ImageIO.write(mergedImage, "jpg", byteArrayOutputStream);
    } catch (IOException e) {
      return null;
    InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return inputStream;

Open in new window

The server only accepts the image of size less than 1MB so if the image size if more than 1 MB than i need to do some image compression etc.

Please suggest what are the possibilities and things i can do ?


Avatar of undefined
Last Comment

8/22/2022 - Mon