howto: java.io.Image to InputStream

7,549 views
Skip to first unread message

koraytaylan

unread,
Dec 19, 2010, 7:06:06 PM12/19/10
to play-fr...@googlegroups.com
hi,

i am trying to render thumbnail images. i found some posts about it but couldn't find any real samples.

i have a file i am loading it and getting a scaled instance then what? somehow i need to convert it to an inputstream.

Image img = ImageIO.read(new java.io.File(path));
img = img.getScaledInstance(80, 60, Image.SCALE_FAST);
//some process needed here.
renderBinary(is, "image.jpg", false);

thanks.

Daniel Guryca

unread,
Dec 20, 2010, 3:39:10 AM12/20/10
to play-fr...@googlegroups.com
Hi,

http://stackoverflow.com/questions/4251383/how-to-convert-bufferedimage-to-inputstream

Daniel

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.

koraytaylan

unread,
Dec 20, 2010, 5:29:08 AM12/20/10
to play-fr...@googlegroups.com
it says,

You need to save the BufferedImage to a ByteArrayOutputStream using the ImageIO class, then create a ByteArrayInputStream from toByteArray().

well, how? i can't see any method in ImageIO returning a ByteArrayOutputStream.

second answer a bit more helpful but

buffer = ((DataBufferByte)(bufferedImage).getRaster().getDataBuffer()).getData();

throws,

ClassCastException occured : java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte 

i don't really understand why handling streams in java is so confusing. i am also trying to zip multiple images into a response stream and it's another breathtaking pain. it definitely shouldn't be this hard i guess... i'm actually a .net guy for years and things are making a lot more sense and pretty straightforward with c#.

Daniel Guryca

unread,
Dec 20, 2010, 6:34:19 AM12/20/10
to play-fr...@googlegroups.com
Hi,

First, google is your friend.
Yes java has a bit confusing streams handling.

Solution for you:

BufferedImage bi = ImageIO.read(new File("myFile.jpg")); 

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos );
baos.flush();

byte[] imageInByte = baos.toByteArray();
baos.close();

InputStream is = new ByteArrayInputStream(imageInByte);


Daniel

--
Reply all
Reply to author
Forward
0 new messages