Start New Discussion within our Software Development Community

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<ImageWriter> 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?

Have a look at ByteArrayOutputStream. It's an OutputStream that writes the data directly to an in-memory self-expanding byte array, from which you can access the bytes directly.

This article has been dead for over six months. Start a new discussion instead.