Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.Image To InputStream

I'm resizing a image and I need to return a InputStream object

public InputStream resize(InputStream input, int maxSize){
   BufferedImage image = ImageIO.read(input);
   double scale = (double) image.getWidth()/maxSize;
   Image scaledImage = image.getScaledInstance( (int) (image.getWidth() * scale), (int) (image.getHeight() * scale), Image.SCALE_SMOOTH);
   InputStream ret = (InputStream) scaledImage;//this is wrong cast
   retrun ret;
}

how can I convert a Image to a InputStream?

like image 280
xedo Avatar asked May 16 '26 04:05

xedo


1 Answers

You can use this code for converting:

 BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),    BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outStream); 
InputStream is = new ByteArrayInputStream(outStream.toByteArray());
like image 118
Jens Avatar answered May 18 '26 14:05

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!