Example usage for java.awt.image Raster getDataBuffer

List of usage examples for java.awt.image Raster getDataBuffer

Introduction

In this page you can find the example usage for java.awt.image Raster getDataBuffer.

Prototype

public DataBuffer getDataBuffer() 

Source Link

Document

Returns the DataBuffer associated with this Raster.

Usage

From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

/**
 * Utility method for creating a BufferedImage from a source raster Currently only Float->Byte and Byte->Byte are supported. Will throw an
 * {@link UnsupportedOperationException} if the conversion is not supported.
 * /*from www .  j av  a 2 s .c  o  m*/
 * @param raster
 * @param imageType
 * @return
 */
public static BufferedImage rasterToBufferedImage(Raster raster, ImageTypeSpecifier imageType) {
    if (imageType == null) {
        if (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE)
            imageType = ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE, false);
        else
            throw new IllegalArgumentException("unable to dynamically determine the imageType");
    }
    // create a new buffered image, for display
    BufferedImage bufImage = imageType.createBufferedImage(raster.getWidth(), raster.getHeight());

    if (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_USHORT
            && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE) {
        // convert short pixels to bytes
        short[] shortData = ((DataBufferUShort) raster.getDataBuffer()).getData();
        byte[] byteData = ((DataBufferByte) bufImage.getWritableTile(0, 0).getDataBuffer()).getData();
        ImageIOUtils.shortToByteBuffer(shortData, byteData, 1, raster.getNumBands());
    } else if (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_FLOAT
            && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE) {
        // convert float pixels to bytes
        float[] floatData = ((DataBufferFloat) raster.getDataBuffer()).getData();
        byte[] byteData = ((DataBufferByte) bufImage.getWritableTile(0, 0).getDataBuffer()).getData();
        ImageIOUtils.floatToByteBuffer(floatData, byteData, 1, raster.getNumBands());
    } else if (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_DOUBLE
            && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE) {
        // convert double pixels to bytes
        double[] doubleData = ((DataBufferDouble) raster.getDataBuffer()).getData();
        byte[] byteData = ((DataBufferByte) bufImage.getWritableTile(0, 0).getDataBuffer()).getData();
        ImageIOUtils.doubleToByteBuffer(doubleData, byteData, 1, raster.getNumBands());
    } else if ((raster.getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE
            && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_BYTE)
            || (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_USHORT
                    && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_USHORT)
            || (raster.getDataBuffer().getDataType() == DataBuffer.TYPE_SHORT
                    && bufImage.getRaster().getDataBuffer().getDataType() == DataBuffer.TYPE_SHORT)) {
        bufImage.setData(raster);
    } else {
        throw new UnsupportedOperationException(
                "Unable to convert raster type to bufferedImage type: " + raster.getDataBuffer().getDataType()
                        + " ==> " + bufImage.getRaster().getDataBuffer().getDataType());
    }
    return bufImage;
}

From source file:GraphicsUtil.java

/**
 * Coerces <tt>ras</tt> to be writable.  The returned Raster continues to
 * reference the DataBuffer from ras, so modifications to the returned
 * WritableRaster will be seen in ras.<p>
 *
 * You can specify a new location for the returned WritableRaster, this
 * is especially useful for constructing BufferedImages which require
 * the Raster to be at (0,0).//from  w  w  w . ja va2  s .c  o  m
 *
 * This method should only be used if you need a WritableRaster due to
 * an interface (such as to construct a BufferedImage), but have no
 * intention of modifying the contents of the returned Raster.  If
 * you have any doubt about other users of the data in <tt>ras</tt>,
 * use copyRaster (above).
 *
 * @param ras The raster to make writable.
 *
 * @param minX The x location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @param minY The y location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @return A Writable version of <tT>ras</tt> with it's upper left
 *         hand coordinate set to minX, minY (shares it's DataBuffer
 *         with <tt>ras</tt>).
 */
public static WritableRaster makeRasterWritable(Raster ras, int minX, int minY) {
    WritableRaster ret = Raster.createWritableRaster(ras.getSampleModel(), ras.getDataBuffer(),
            new Point(0, 0));
    ret = ret.createWritableChild(ras.getMinX() - ras.getSampleModelTranslateX(),
            ras.getMinY() - ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null);
    return ret;
}

From source file:omr.jai.TestImage3.java

    public static PlanarImage decodeImage (String[] rows)
    {/*from  www.  j ava2  s.  co m*/
        // Create the DataBuffer to hold the pixel samples
        final int width = rows[0].length();
        final int height = rows.length;

        // Create Raster
        Raster raster;
        if (true) {
            raster = Raster.createPackedRaster
            (DataBuffer.TYPE_INT, width, height,
             new int[] {0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000},// bandMasks RGBA
             null);
        } else {
            raster = Raster.createInterleavedRaster
                (DataBuffer.TYPE_BYTE, width, height,
                 4,// num of bands
                 null);
        }

        // Populate the data buffer
        DataBuffer dataBuffer = raster.getDataBuffer();
        int index = 0;
        for (String row : rows) {
            for (int x = 0; x < width; x++) {
                int argb = toARGB(row.charAt(x));
                dataBuffer.setElem(index, argb);
                index++;
            }
        }

        // Dump
//         final int size = width * height;
//         System.out.println("DataBuffer :");
//         for (int i = 0; i < size; i++) {
//             if (i % width == 0) {
//                 System.out.println();
//             }
//             System.out.print(String.format("%8x ", dataBuffer.getElem(i)));
//         }
//         System.out.println();

        // Create the image
        BufferedImage bufferedImage = new BufferedImage
                (width, height, BufferedImage.TYPE_INT_ARGB);
        bufferedImage.setData(raster);

        // Dump
//         System.out.println("BufferedImage :");
//         for (int y = 0; y < height; y++) {
//             System.out.println();
//             for (int x = 0; x < width; x++) {
//                 System.out.print(String.format("%8x ", bufferedImage.getRGB(x, y)));
//             }
//         }
//         System.out.println();

        return PlanarImage.wrapRenderedImage(bufferedImage);
    }

From source file:GraphicsUtil.java

/**
 * Creates a new raster that has a <b>copy</b> of the data in
 * <tt>ras</tt>.  This is highly optimized for speed.  There is
 * no provision for changing any aspect of the SampleModel.
 * However you can specify a new location for the returned raster.
 *
 * This method should be used when you need to change the contents
 * of a Raster that you do not "own" (ie the result of a
 * <tt>getData</tt> call).//ww  w .j  a v a2s.  c o  m
 *
 * @param ras The Raster to copy.
 *
 * @param minX The x location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @param minY The y location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @return    A writable copy of <tt>ras</tt>
 */
public static WritableRaster copyRaster(Raster ras, int minX, int minY) {
    WritableRaster ret = Raster.createWritableRaster(ras.getSampleModel(), new Point(0, 0));
    ret = ret.createWritableChild(ras.getMinX() - ras.getSampleModelTranslateX(),
            ras.getMinY() - ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null);

    // Use System.arraycopy to copy the data between the two...
    DataBuffer srcDB = ras.getDataBuffer();
    DataBuffer retDB = ret.getDataBuffer();
    if (srcDB.getDataType() != retDB.getDataType()) {
        throw new IllegalArgumentException("New DataBuffer doesn't match original");
    }
    int len = srcDB.getSize();
    int banks = srcDB.getNumBanks();
    int[] offsets = srcDB.getOffsets();
    for (int b = 0; b < banks; b++) {
        switch (srcDB.getDataType()) {
        case DataBuffer.TYPE_BYTE: {
            DataBufferByte srcDBT = (DataBufferByte) srcDB;
            DataBufferByte retDBT = (DataBufferByte) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_INT: {
            DataBufferInt srcDBT = (DataBufferInt) srcDB;
            DataBufferInt retDBT = (DataBufferInt) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_SHORT: {
            DataBufferShort srcDBT = (DataBufferShort) srcDB;
            DataBufferShort retDBT = (DataBufferShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_USHORT: {
            DataBufferUShort srcDBT = (DataBufferUShort) srcDB;
            DataBufferUShort retDBT = (DataBufferUShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        }
    }

    return ret;
}

From source file:GraphicsUtil.java

/**
 * Creates a new raster that has a <b>copy</b> of the data in
 * <tt>ras</tt>.  This is highly optimized for speed.  There is
 * no provision for changing any aspect of the SampleModel.
 * However you can specify a new location for the returned raster.
 *
 * This method should be used when you need to change the contents
 * of a Raster that you do not "own" (ie the result of a
 * <tt>getData</tt> call).//  ww w  .  j a va 2s  . c  o m
 *
 * @param ras The Raster to copy.
 *
 * @param minX The x location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @param minY The y location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @return    A writable copy of <tt>ras</tt>
 */
public static WritableRaster copyRaster(Raster ras, int minX, int minY) {
    WritableRaster ret = Raster.createWritableRaster(ras.getSampleModel(), new Point(0, 0));
    ret = ret.createWritableChild(ras.getMinX() - ras.getSampleModelTranslateX(),
            ras.getMinY() - ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null);

    // Use System.arraycopy to copy the data between the two...
    DataBuffer srcDB = ras.getDataBuffer();
    DataBuffer retDB = ret.getDataBuffer();
    if (srcDB.getDataType() != retDB.getDataType()) {
        throw new IllegalArgumentException("New DataBuffer doesn't match original");
    }
    int len = srcDB.getSize();
    int banks = srcDB.getNumBanks();
    int[] offsets = srcDB.getOffsets();
    for (int b = 0; b < banks; b++) {
        switch (srcDB.getDataType()) {
        case DataBuffer.TYPE_BYTE: {
            DataBufferByte srcDBT = (DataBufferByte) srcDB;
            DataBufferByte retDBT = (DataBufferByte) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
            break;
        }
        case DataBuffer.TYPE_INT: {
            DataBufferInt srcDBT = (DataBufferInt) srcDB;
            DataBufferInt retDBT = (DataBufferInt) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
            break;
        }
        case DataBuffer.TYPE_SHORT: {
            DataBufferShort srcDBT = (DataBufferShort) srcDB;
            DataBufferShort retDBT = (DataBufferShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
            break;
        }
        case DataBuffer.TYPE_USHORT: {
            DataBufferUShort srcDBT = (DataBufferUShort) srcDB;
            DataBufferUShort retDBT = (DataBufferUShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
            break;
        }
        }
    }

    return ret;
}

From source file:DataBufferGrabber.java

protected void paintComponent(Graphics g) {
    // create an image
    BufferedImage bImg = new BufferedImage(SWATCH_SIZE, SWATCH_SIZE, BufferedImage.TYPE_INT_RGB);
    Graphics gImage = bImg.getGraphics();
    gImage.setColor(Color.WHITE);
    gImage.fillRect(0, 0, SWATCH_SIZE, SWATCH_SIZE);

    // Time how long it takes to copy the managed version
    long managedTime = copyImage(g, bImg, 0, 0);
    System.out.println("Managed: " + managedTime + " ms");

    // Now grab the pixel array, change the colors, re-run the test
    Raster raster = bImg.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int pixels[] = dataBuffer.getData();
    for (int i = 0; i < pixels.length; ++i) {
        // Make all pixels black
        pixels[i] = 0;/*from   w w w . j  a  v  a2s .  c o m*/
    }

    // Time this un-managed copy
    long unmanagedTime = copyImage(g, bImg, SWATCH_SIZE, 0);
    System.out.println("Unmanaged: " + unmanagedTime + " ms");
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*from  w  ww . j  a  va  2s .  c o m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:GraphicsUtil.java

/**
 * An internal optimized version of copyData designed to work on
 * Integer packed data with a SinglePixelPackedSampleModel.  Only
 * the region of overlap between src and dst is copied.
 *
 * Calls to this should be preflighted with is_INT_PACK_Data
 * on both src and dest (requireAlpha can be false).
 *
 * @param src The source of the data/*from w w  w .  j  a  va  2 s . com*/
 * @param dst The destination for the data.
 */
public static void copyData_INT_PACK(Raster src, WritableRaster dst) {
    // System.out.println("Fast copyData");
    int x0 = dst.getMinX();
    if (x0 < src.getMinX())
        x0 = src.getMinX();

    int y0 = dst.getMinY();
    if (y0 < src.getMinY())
        y0 = src.getMinY();

    int x1 = dst.getMinX() + dst.getWidth() - 1;
    if (x1 > src.getMinX() + src.getWidth() - 1)
        x1 = src.getMinX() + src.getWidth() - 1;

    int y1 = dst.getMinY() + dst.getHeight() - 1;
    if (y1 > src.getMinY() + src.getHeight() - 1)
        y1 = src.getMinY() + src.getHeight() - 1;

    int width = x1 - x0 + 1;
    int height = y1 - y0 + 1;

    SinglePixelPackedSampleModel srcSPPSM;
    srcSPPSM = (SinglePixelPackedSampleModel) src.getSampleModel();

    final int srcScanStride = srcSPPSM.getScanlineStride();
    DataBufferInt srcDB = (DataBufferInt) src.getDataBuffer();
    final int[] srcPixels = srcDB.getBankData()[0];
    final int srcBase = (srcDB.getOffset()
            + srcSPPSM.getOffset(x0 - src.getSampleModelTranslateX(), y0 - src.getSampleModelTranslateY()));

    SinglePixelPackedSampleModel dstSPPSM;
    dstSPPSM = (SinglePixelPackedSampleModel) dst.getSampleModel();

    final int dstScanStride = dstSPPSM.getScanlineStride();
    DataBufferInt dstDB = (DataBufferInt) dst.getDataBuffer();
    final int[] dstPixels = dstDB.getBankData()[0];
    final int dstBase = (dstDB.getOffset()
            + dstSPPSM.getOffset(x0 - dst.getSampleModelTranslateX(), y0 - dst.getSampleModelTranslateY()));

    if ((srcScanStride == dstScanStride) && (srcScanStride == width)) {
        // System.out.println("VERY Fast copyData");

        System.arraycopy(srcPixels, srcBase, dstPixels, dstBase, width * height);
    } else if (width > 128) {
        int srcSP = srcBase;
        int dstSP = dstBase;
        for (int y = 0; y < height; y++) {
            System.arraycopy(srcPixels, srcSP, dstPixels, dstSP, width);
            srcSP += srcScanStride;
            dstSP += dstScanStride;
        }
    } else {
        for (int y = 0; y < height; y++) {
            int srcSP = srcBase + y * srcScanStride;
            int dstSP = dstBase + y * dstScanStride;
            for (int x = 0; x < width; x++)
                dstPixels[dstSP++] = srcPixels[srcSP++];
        }
    }
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

/**
 * Paint a bitmap at the current cursor position. The bitmap must be a monochrome
 * (1-bit) bitmap image.//from ww w .  j a  v  a  2  s  . c om
 * @param img the bitmap image (must be 1-bit b/w)
 * @param resolution the resolution of the image (must be a PCL resolution)
 * @throws IOException In case of an I/O error
 */
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException {
    if (!isValidPCLResolution(resolution)) {
        throw new IllegalArgumentException("Invalid PCL resolution: " + resolution);
    }
    boolean monochrome = isMonochromeImage(img);
    if (!monochrome) {
        throw new IllegalArgumentException("img must be a monochrome image");
    }

    setRasterGraphicsResolution(resolution);
    writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A");
    Raster raster = img.getData();

    Encoder encoder = new Encoder(img);
    // Transfer graphics data
    int imgw = img.getWidth();
    IndexColorModel cm = (IndexColorModel) img.getColorModel();
    if (cm.getTransferType() == DataBuffer.TYPE_BYTE) {
        DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
        MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
                img.getWidth(), img.getHeight(), 1);
        if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) {
            //Optimized packed encoding
            byte[] buf = dataBuffer.getData();
            int scanlineStride = packedSampleModel.getScanlineStride();
            int idx = 0;
            int c0 = toGray(cm.getRGB(0));
            int c1 = toGray(cm.getRGB(1));
            boolean zeroIsWhite = c0 > c1;
            for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
                for (int x = 0, maxx = scanlineStride; x < maxx; x++) {
                    if (zeroIsWhite) {
                        encoder.add8Bits(buf[idx]);
                    } else {
                        encoder.add8Bits((byte) ~buf[idx]);
                    }
                    idx++;
                }
                encoder.endLine();
            }
        } else {
            //Optimized non-packed encoding
            for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
                byte[] line = (byte[]) raster.getDataElements(0, y, imgw, 1, null);
                for (int x = 0, maxx = imgw; x < maxx; x++) {
                    encoder.addBit(line[x] == 0);
                }
                encoder.endLine();
            }
        }
    } else {
        //Safe but slow fallback
        for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
            for (int x = 0, maxx = imgw; x < maxx; x++) {
                int sample = raster.getSample(x, y, 0);
                encoder.addBit(sample == 0);
            }
            encoder.endLine();
        }
    }

    // End raster graphics
    writeCommand("*rB");
}

From source file:org.apache.xmlgraphics.ps.PSImageUtils.java

/**
 * Extracts a packed RGB integer array of a RenderedImage.
 * @param img the image//from   ww  w .  j a  v  a 2s  . c o m
 * @param startX the starting X coordinate
 * @param startY the starting Y coordinate
 * @param w the width of the cropped image
 * @param h the height of the cropped image
 * @param rgbArray the prepared integer array to write to
 * @param offset offset in the target array
 * @param scansize width of a row in the target array
 * @return the populated integer array previously passed in as rgbArray parameter
 */
public static int[] getRGB(RenderedImage img, int startX, int startY, int w, int h, int[] rgbArray, int offset,
        int scansize) {
    Raster raster = img.getData();
    int yoff = offset;
    int off;
    Object data;
    int nbands = raster.getNumBands();
    int dataType = raster.getDataBuffer().getDataType();
    switch (dataType) {
    case DataBuffer.TYPE_BYTE:
        data = new byte[nbands];
        break;
    case DataBuffer.TYPE_USHORT:
        data = new short[nbands];
        break;
    case DataBuffer.TYPE_INT:
        data = new int[nbands];
        break;
    case DataBuffer.TYPE_FLOAT:
        data = new float[nbands];
        break;
    case DataBuffer.TYPE_DOUBLE:
        data = new double[nbands];
        break;
    default:
        throw new IllegalArgumentException("Unknown data buffer type: " + dataType);
    }

    if (rgbArray == null) {
        rgbArray = new int[offset + h * scansize];
    }

    ColorModel colorModel = img.getColorModel();
    for (int y = startY; y < startY + h; y++, yoff += scansize) {
        off = yoff;
        for (int x = startX; x < startX + w; x++) {
            rgbArray[off++] = colorModel.getRGB(raster.getDataElements(x, y, data));
        }
    }

    return rgbArray;
}