troubleshooting Question

Compress a BufferedImage in java

Avatar of Rohit Bajaj
Rohit BajajFlag for India asked on
Java
12 Comments1 Solution171 ViewsLast Modified:
Hi,
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()));
        imageList.add(image);
        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;
  }

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);
      byteArrayOutputStream.flush();
    } catch (IOException e) {
      return null;
    }
    InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return inputStream;
  }

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 ?

Thanks
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 12 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros