ImageWriter extends AbstractDataWriter { public void write(DataSource data, OutputStream output) throws IOException { int w = data.getColumnCount(); int h = data.getRowCount(); double factor = this.<Number>getSetting("factor").doubleValue(); double offset = this.<Number>getSetting("offset").doubleValue(); byte[] pixelData = new byte[w*h]; int pos = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { Comparable<?> cell = data.get(x, y); if (!(cell instanceof Number)) { continue; } Number numericCell = (Number) cell; double value = numericCell.doubleValue()*factor + offset; byte v = (byte) Math.round(MathUtils.limit(value, 0.0, 255.0)); pixelData[pos++] = v; } } BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); image.getRaster().setDataElements(0, 0, w, h, pixelData); Iterator<javax.imageio.ImageWriter> writers = ImageIO.getImageWritersByMIMEType(getMimeType()); try { javax.imageio.ImageWriter writer = writers.next(); writer.setOutput(ImageIO.createImageOutputStream(output)); writer.write(image); } catch (NoSuchElementException e) { throw new IOException(MessageFormat.format( "No writer found for MIME type {0}.", getMimeType())); } } ImageWriter(String mimeType); void write(DataSource data, OutputStream output);  }
@Test public void testWriter() throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); DataWriter writer = DataWriterFactory.getInstance().get("image/png"); writer.write(data, output); ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); BufferedImage image = ImageIO.read(input); assertEquals(data.getColumnCount(), image.getWidth()); assertEquals(data.getRowCount(), image.getHeight()); byte[] imageData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < imageData.length; i++) { int col = i % image.getWidth(); int row = i / image.getWidth(); double expected = ((Number) data.get(col, row)).doubleValue(); double value = imageData[i]; if (value < 0.0) { value += 256.0; } assertEquals(expected, value, DELTA); } }