Skip to content

Instantly share code, notes, and snippets.

@werbth
Last active December 24, 2022 04:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save werbth/4b1cf7567657cd64c71eb08099544f35 to your computer and use it in GitHub Desktop.
Save werbth/4b1cf7567657cd64c71eb08099544f35 to your computer and use it in GitHub Desktop.
Given a jpeg image as InputStream, resize it and return another InputStream.
// formatName: the image format name (jpeg, png)
public static InputStream resizeImage(InputStream inputStream, int width, int height, String formatName) throws IOException {
BufferedImage sourceImage = ImageIO.read(inputStream);
Image thumbnail = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage bufferedThumbnail = new BufferedImage(thumbnail.getWidth(null),
thumbnail.getHeight(null),
BufferedImage.TYPE_INT_RGB);
bufferedThumbnail.getGraphics().drawImage(thumbnail, 0, 0, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedThumbnail, formatName, baos);
return new ByteArrayInputStream(baos.toByteArray());
}
@LeRoiDavid
Copy link

thank's

@roshanupreti
Copy link

Does this only work for JPEG or any kind of image?

@werbth
Copy link
Author

werbth commented Aug 18, 2020

It works for other formats as well. For instance, I have tested with png. I have updated the gist.

@anielsonrf
Copy link

Muito Obrigado.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment