Search This Blog

Monday, August 15, 2011

Convert Image To Bytes

Using the basic principle in this code:





		try {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
BufferedImage[] screenshots = new BufferedImage[gs.length];

ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
if (iter.hasNext())
writer = iter.next();

ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.1F);

DisplayMode mode;
Rectangle bounds;

for (int i = 0; i < gs.length; i++) {
mode = gs[i].getDisplayMode();
bounds = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
screenshots[i] = new Robot(gs[i]).createScreenCapture(bounds);

writer.setOutput(new FileImageOutputStream(new File("image "
+ i + ".jpeg")));
IIOImage image = new IIOImage(screenshots[i], null, null);
writer.write(null, image, iwp);
}

} catch (Exception ex) {
ex.printStackTrace();
}




How would I go about converting the output to a byte array, instead of writing the image to file?


I was thinking of first writing the image to file, then reading the images as bytes using FileInputStream, but I'm sure there is a better way of doing it, like, writing the image to memory, then reading the bytes (I have no idea how to accomplish this in java, but in C# I'd just use MemoryStream to write the bytes, then open a BinaryReader stream using the same MemoryStream object)


Does anybody have any ideas?

http://bit.ly/qyuHAr

No comments:

Post a Comment