troubleshooting Question

Compress a BufferedImage in java

Avatar of Rohit Bajaj
Rohit BajajFlag for India asked on
12 Comments1 Solution171 ViewsLast Modified:
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 = 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 ?


Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
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