3

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?

1 Answer 1

8

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());
Sign up to request clarification or add additional context in comments.

2 Comments

sorry I wrote a misstake. What I want to convert is the scaldedImage, is a java.io.Image
@xedo: I have changed my answer. Convert you Image to an BufferedImage first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.