Example usage for java.awt.image Raster getDataElements

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

Introduction

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

Prototype

public Object getDataElements(int x, int y, int w, int h, Object outData) 

Source Link

Document

Returns the pixel data for the specified rectangle of pixels in a primitive array of type TransferType.

Usage

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

public static int[][] imageToPixels(BufferedImage image) {
    if (image == null) {
        return null;
    }/*from w w  w. j  a  v  a 2  s .c o  m*/
    int w = image.getWidth();
    int h = image.getHeight();
    int[][] pixels = new int[w][h];
    Raster raster = image.getRaster();
    if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
        byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
        int bytesPerPixel = (bytes.length / (w * h));
        ColorModel colorModel = image.getColorModel();
        byte[] buf = new byte[bytesPerPixel];
        for (int x = 0; x < w; ++x) {
            for (int y = 0; y < h; ++y) {
                System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                pixels[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
            }
        }
        return pixels;
    } else {
        throw new RuntimeException("transfer type " + raster.getTransferType() + " not implemented yet");
    }
}

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

private static List<RectangularRegion> findSubImageInImage(BufferedImage subImage, BufferedImage image,
        int max) {
    Map<Integer, List<Point>> rgb2offsets = new HashMap<Integer, List<Point>>();
    int sw = subImage.getWidth();
    int sh = subImage.getHeight();
    for (int x = 0; x < sw; ++x) {
        for (int y = 0; y < sh; ++y) {
            int argb = subImage.getRGB(x, y);
            int a = argb >>> 24;
            if (a == 255) {
                Integer rgb = argb & 0xFFFFFF;
                List<Point> offsets = rgb2offsets.get(rgb);
                if (offsets == null) {
                    offsets = new ArrayList<Point>();
                    rgb2offsets.put(rgb, offsets);
                }//from w  ww  .ja  va  2s  . c o  m
                offsets.add(new Point(x, y));
            }
        }
    }
    List<RectangularRegion> result = new ArrayList<RectangularRegion>();
    int w = image.getWidth();
    int h = image.getHeight();
    int[][] p = new int[w][h];
    Raster raster = image.getRaster();
    if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
        byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
        int bytesPerPixel = (bytes.length / (w * h));
        ColorModel colorModel = image.getColorModel();
        byte[] buf = new byte[bytesPerPixel];
        for (int x = 0; x < w; ++x) {
            for (int y = 0; y < h; ++y) {
                System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                p[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
            }
        }
    } else if (raster.getTransferType() == DataBuffer.TYPE_INT) {
        for (int x = 0; x < w; ++x) {
            p[x] = (int[]) raster.getDataElements(x, 0, 1, h, null);
        }
    } else {
        throw new RuntimeException("findSubImageInImage not implemented for image transfer type "
                + raster.getTransferType() + " yet.");
    }
    for (int x = 0; x < w; ++x) {
        for (int y = 0; y < h; ++y) {
            Iterator<Map.Entry<Integer, List<Point>>> i = rgb2offsets.entrySet().iterator();
            compareWithSubImageLoop: while (i.hasNext()) {
                Map.Entry<Integer, List<Point>> mapEntry = i.next();
                int expectedRgb = mapEntry.getKey();
                for (Point offset : mapEntry.getValue()) {
                    int xx = x + offset.x;
                    int yy = y + offset.y;
                    if (xx >= w || yy >= h || expectedRgb != p[xx][yy]) {
                        break compareWithSubImageLoop;
                    }
                }
                if (!i.hasNext()) {
                    result.add(new RectangularRegion(x, y, x + (sw - 1), y + (sh - 1)));
                    if (result.size() == max) {
                        return result;
                    }
                }
            }
        }
    }
    return result;
}

From source file:ImageOpByRomain.java

/**
 * <p>/*from  w  ww .j  a va2s  . c o  m*/
 * Returns an array of pixels, stored as integers, from a
 * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
 * area defined by a location and two dimensions. Calling this method on an
 * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and
 * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.
 * </p>
 * 
 * @param img
 *            the source image
 * @param x
 *            the x location at which to start grabbing pixels
 * @param y
 *            the y location at which to start grabbing pixels
 * @param w
 *            the width of the rectangle of pixels to grab
 * @param h
 *            the height of the rectangle of pixels to grab
 * @param pixels
 *            a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers
 *         otherwise
 * @throws IllegalArgumentException
 *             is <code>pixels</code> is non-null and of length &lt; w*h
 */
public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) {
    if (w == 0 || h == 0) {
        return new int[0];
    }

    if (pixels == null) {
        pixels = new int[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" + " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) {
        Raster raster = img.getRaster();
        return (int[]) raster.getDataElements(x, y, w, h, pixels);
    }

    // Unmanages the image
    return img.getRGB(x, y, w, h, pixels, 0, w);
}

From source file:main.MapKit.java

@Override
public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel,
        RenderingHints hints) {/*from   w  ww.ja va 2  s .  co m*/
    return new CompositeContext() {
        @Override
        public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
            if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT
                    || dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT
                    || dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) {
                throw new IllegalStateException("Source and destination must store pixels as INT.");
            }

            int width = Math.min(src.getWidth(), dstIn.getWidth());
            int height = Math.min(src.getHeight(), dstIn.getHeight());

            int[] srcPixel = new int[4];
            int[] dstPixel = new int[4];
            int[] srcPixels = new int[width];
            int[] dstPixels = new int[width];

            for (int y = 0; y < height; y++) {
                src.getDataElements(0, y, width, 1, srcPixels);
                dstIn.getDataElements(0, y, width, 1, dstPixels);

                for (int x = 0; x < width; x++) {
                    // pixels are stored as INT_ARGB
                    // our arrays are [R, G, B, A]
                    int pixel = srcPixels[x];
                    srcPixel[0] = (pixel >> 16) & 0xFF;
                    srcPixel[1] = (pixel >> 8) & 0xFF;
                    srcPixel[2] = (pixel >> 0) & 0xFF;
                    srcPixel[3] = (pixel >> 24) & 0xFF;

                    pixel = dstPixels[x];
                    dstPixel[0] = (pixel >> 16) & 0xFF;
                    dstPixel[1] = (pixel >> 8) & 0xFF;
                    dstPixel[2] = (pixel >> 0) & 0xFF;
                    dstPixel[3] = (pixel >> 24) & 0xFF;

                    int[] result = new int[] { (srcPixel[0] * dstPixel[0]) >> 8,
                            (srcPixel[1] * dstPixel[1]) >> 8, (srcPixel[2] * dstPixel[2]) >> 8,
                            (srcPixel[3] * dstPixel[3]) >> 8 };

                    // mixes the result with the opacity
                    dstPixels[x] = (result[3]) << 24 | (result[0]) << 16 | (result[1]) << 8 | (result[2]);
                }
                dstOut.setDataElements(0, y, width, 1, dstPixels);
            }
        }

        @Override
        public void dispose() {
            // empty
        }
    };
}

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   w  w w  .j  a  v a 2s.c o  m
 * @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.mrgeo.data.raster.RasterWritable.java

private static byte[] rasterToBytes(final Raster raster) {
    final int datatype = raster.getTransferType();

    byte[] pixels;

    final Object elements = raster.getDataElements(raster.getMinX(), raster.getMinY(), raster.getWidth(),
            raster.getHeight(), null);//from   w w w  . ja va 2s  . c  o m

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        pixels = (byte[]) elements;
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final float[] floatElements = (float[]) elements;

        pixels = new byte[floatElements.length * RasterUtils.FLOAT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final FloatBuffer floatbuff = bytebuff.asFloatBuffer();
        floatbuff.put(floatElements);

        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final double[] doubleElements = (double[]) elements;

        pixels = new byte[doubleElements.length * RasterUtils.DOUBLE_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final DoubleBuffer doubleBuff = bytebuff.asDoubleBuffer();
        doubleBuff.put(doubleElements);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final int[] intElements = (int[]) elements;

        pixels = new byte[intElements.length * RasterUtils.INT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final IntBuffer intBuff = bytebuff.asIntBuffer();
        intBuff.put(intElements);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final short[] shortElements = (short[]) elements;

        pixels = new byte[shortElements.length * RasterUtils.SHORT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final ShortBuffer shortbuff = bytebuff.asShortBuffer();
        shortbuff.put(shortElements);

        break;
    }
    default:
        throw new RasterWritableException("Error trying to append raster.  Bad raster data type");
    }

    return pixels;
}