Example usage for java.awt.image BufferedImage getRaster

List of usage examples for java.awt.image BufferedImage getRaster

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getRaster.

Prototype

public WritableRaster getRaster() 

Source Link

Document

Returns the WritableRaster .

Usage

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  w w. ja v a2s  .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:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java

@Override
public boolean drawImage(Image img, int x1, int y1, ImageObserver observer) {
    PSGenerator tmp = gen;/*from   w  w  w . jav  a2s.c o  m*/
    if (gen instanceof PSDocumentHandler.FOPPSGenerator) {
        PSDocumentHandler.FOPPSGenerator fopGen = (PSDocumentHandler.FOPPSGenerator) tmp;
        PSDocumentHandler handler = fopGen.getHandler();
        if (handler.getPSUtil().isOptimizeResources()) {
            try {
                final int width = img.getWidth(observer);
                final int height = img.getHeight(observer);
                if (width == -1 || height == -1) {
                    return false;
                }
                BufferedImage buf = getImage(width, height, img, observer);
                if (buf == null) {
                    return false;
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataBufferInt db = (DataBufferInt) buf.getRaster().getDataBuffer();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeInt(width);
                dos.writeInt(height);
                for (int i : db.getData()) {
                    dos.writeInt(i);
                }
                String format = DataBufferInt.class.getName();
                int hash = Arrays.hashCode(bos.toByteArray());
                URI uri = fopGen.getImages().get(hash);
                if (uri == null) {
                    uri = new TempResourceURIGenerator("img" + hash + "." + format).generate();
                    fopGen.getImages().put(hash, uri);
                    BufferedOutputStream outputStream = fopGen.getTempStream(uri);
                    outputStream.write(bos.toByteArray());
                    outputStream.close();
                }
                PSResource form = handler.getFormForImage(uri.toASCIIString());
                ImageInfo info = new ImageInfo(uri.toASCIIString(), "image/" + format);
                ImageSize size = new ImageSize(width, height, handler.getUserAgent().getTargetResolution());
                size.calcSizeFromPixels();
                info.setSize(size);
                float res = handler.getUserAgent().getSourceResolution() / 72;
                Rectangle rect = new Rectangle(0, 0, (int) (size.getWidthMpt() * res),
                        (int) (size.getHeightMpt() * res));
                gen.saveGraphicsState();
                gen.concatMatrix(getTransform());
                writeClip(getClip());
                PSImageUtils.drawForm(form, info, rect, gen);
                gen.restoreGraphicsState();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    }
    return super.drawImage(img, x1, y1, observer);
}

From source file:org.eclipse.swt.snippets.Snippet156.java

static BufferedImage convertToAWT(ImageData data) {
    ColorModel colorModel = null;
    PaletteData palette = data.palette;//from w ww .  java 2  s .c  om
    if (palette.isDirect) {
        colorModel = new DirectColorModel(data.depth, palette.redMask, palette.greenMask, palette.blueMask);
        BufferedImage bufferedImage = new BufferedImage(colorModel,
                colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                int pixel = data.getPixel(x, y);
                RGB rgb = palette.getRGB(pixel);
                bufferedImage.setRGB(x, y, rgb.red << 16 | rgb.green << 8 | rgb.blue);
            }
        }
        return bufferedImage;
    } else {
        RGB[] rgbs = palette.getRGBs();
        byte[] red = new byte[rgbs.length];
        byte[] green = new byte[rgbs.length];
        byte[] blue = new byte[rgbs.length];
        for (int i = 0; i < rgbs.length; i++) {
            RGB rgb = rgbs[i];
            red[i] = (byte) rgb.red;
            green[i] = (byte) rgb.green;
            blue[i] = (byte) rgb.blue;
        }
        if (data.transparentPixel != -1) {
            colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue, data.transparentPixel);
        } else {
            colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue);
        }
        BufferedImage bufferedImage = new BufferedImage(colorModel,
                colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
        WritableRaster raster = bufferedImage.getRaster();
        int[] pixelArray = new int[1];
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                int pixel = data.getPixel(x, y);
                pixelArray[0] = pixel;
                raster.setPixel(x, y, pixelArray);
            }
        }
        return bufferedImage;
    }
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage rgb2gray(BufferedImage img) {
    if (img.getType() == BufferedImage.TYPE_INT_ARGB || img.getType() == BufferedImage.TYPE_INT_RGB) {
        int w, h;
        w = img.getWidth();//  www. java  2 s  . c o  m
        h = img.getHeight();
        BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);

        //----------------------------v3.0----------------------
        ColorModel cm = img.getColorModel();
        int pixel, gr;
        int r, g, b;
        WritableRaster raster = out.getRaster();
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                pixel = img.getRGB(x, y);
                r = cm.getRed(pixel);
                g = cm.getGreen(pixel);
                b = cm.getBlue(pixel);

                gr = (int) Math.round(((double) r + (double) g + (double) b) / 3.0);
                raster.setSample(x, y, 0, gr);
            }
        }
        return out;
    }
    return img;
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static void makeTransparent(BufferedImage img, Color trColor) {
    int w = img.getWidth();
    int h = img.getHeight();
    if (img.getType() != BufferedImage.TYPE_INT_ARGB) {
        return;//w  ww  . j a va  2 s  .  c  o  m
    }

    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            if (img.getRaster().getSample(x, y, 0) == trColor.getRed()
                    && img.getRaster().getSample(x, y, 1) == trColor.getGreen()
                    && img.getRaster().getSample(x, y, 2) == trColor.getBlue()) {
                img.getRaster().setSample(x, y, 3, 0);
            }
        }
    }
}

From source file:javafx1.JavaFX1.java

public Image bildLaden() {
        Image zwischenBild = null;

        try {/*from ww  w . j av a  2  s .  c o m*/
            File input = new File("D:/_piCam/bild.jpg");
            //FileInputStream bi = ImageIO.read(input);
            BufferedImage bi = ImageIO.read(input);

            byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
            Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
            mat.put(0, 0, data);

            Mat bild = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC1);
            Imgproc.cvtColor(mat, bild, Imgproc.COLOR_BGR2GRAY);

            byte[] data1 = new byte[bild.rows() * bild.cols() * (int) (bild.elemSize())];
            bild.get(0, 0, data1);
            BufferedImage image1 = new BufferedImage(bild.cols(), bild.rows(), BufferedImage.TYPE_BYTE_GRAY);
            image1.getRaster().setDataElements(0, 0, bild.cols(), bild.rows(), data1);

            File ouptut = new File("D:/xml/grayscale2.jpg");
            //ImageIO.write(image1, "jpg", ouptut);
            BufferedImage gray = image1.getSubimage(0, 0, image1.getTileWidth(), image1.getHeight());
            zwischenBild = SwingFXUtils.toFXImage(gray, null);

        } catch (IOException ex) {
            System.out.println("Fehler beim Bild laden...");
        }
        return zwischenBild;
    }

From source file:org.geowebcache.filter.request.RasterFilter.java

/**
 * Performs a lookup against an internal raster.
 * /*from   www .  ja v  a 2 s. c  o m*/
 * @param grid
 * @param idx
 * @return
 */
private boolean lookup(GridSubset grid, long[] idx) {
    BufferedImage mat = matrices.get(grid.getName())[(int) idx[2]];

    long[] gridCoverage = grid.getCoverage((int) idx[2]);

    // Changing index to top left hand origin
    long x = idx[0] - gridCoverage[0];
    long y = gridCoverage[3] - idx[1];

    return (mat.getRaster().getSample((int) x, (int) y, 0) == 0);
}

From source file:PSDReader.java

protected BufferedImage makeImage(int w, int h, byte[] r, byte[] g, byte[] b, byte[] a) {
    // create image from given plane data
    BufferedImage im = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    int[] data = ((DataBufferInt) im.getRaster().getDataBuffer()).getData();
    int n = w * h;
    int j = 0;/*from  ww  w  .  j a va  2s. c  om*/
    while (j < n) {
        try {
            int ac = a[j] & 0xff;
            int rc = r[j] & 0xff;
            int gc = g[j] & 0xff;
            int bc = b[j] & 0xff;
            data[j] = (((((ac << 8) | rc) << 8) | gc) << 8) | bc;
        } catch (Exception e) {
        }
        j++;
    }
    return im;
}

From source file:tilt.image.Picture.java

/**
 * Generate the text to image links//  ww  w. ja  va  2  s .c  o m
 * @throws ImageException 
 */
void convertToLinks() throws ImageException {
    if (this.linked) {
        page.resetShapes();
        words = null;
    }
    if (words == null)
        convertToWords();
    float ppc = page.pixelsPerChar(text.numChars());
    int[] shapeWidths = page.getShapeWidths();
    int[] wordWidths = text.getWordWidths(ppc);
    Matchup m = new Matchup(wordWidths, shapeWidths);
    try {
        int[][][] alignments = m.align();
        int[] shapeOffsets = page.getShapeLineStarts();
        Word[] wordObjs = text.getWords(ppc);
        BufferedImage clean = ImageIO.read(cleaned);
        page.align(alignments, shapeOffsets, wordObjs, clean.getRaster());
        this.linked = true;
    } catch (Exception e) {
        throw new ImageException(e);
    }
}

From source file:org.tsho.dmc2.core.chart.DmcLyapunovPlot.java

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    CoreStatusEvent statusEv = new CoreStatusEvent(this);
    g2.setPaint(paint);/*  w ww . j  a  va  2s .com*/

    final double parHStep, parVStep;
    double parHLower = domainAxis.getRange().getLowerBound();
    double parHUpper = domainAxis.getRange().getUpperBound();
    double parVLower = rangeAxis.getRange().getLowerBound();
    double parVUpper = rangeAxis.getRange().getUpperBound();

    parHStep = Math.abs(parHUpper - parHLower) / dataArea.getWidth();
    parVStep = Math.abs(parVUpper - parVLower) / dataArea.getHeight();

    final BufferedImage image = new BufferedImage((int) dataArea.getWidth(), (int) dataArea.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int[] data = dataBuffer.getData();

    final double parHStart = parHLower + parHStep / 2;
    final double parVStart = parVUpper - parVStep / 2;

    for (int i = 0; i < (int) dataArea.getWidth(); i++) {
        for (int j = 0; j < (int) dataArea.getHeight(); j++) {

            parameters.put(firstParLabel, parHStart + i * parHStep);
            parameters.put(secondParLabel, parVStart - j * parVStep);

            double[] result;
            int color;

            try {
                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);
            } catch (ModelException e) {
                String mess = "Exception while:\n" + dumpVariableDoubles(parameters)
                        + dumpVariableDoubles(initialPoint);
                throw new ModelException(mess, e);
            }

            if (result == null) {
                System.out.println("i: " + i + " j: " + j);
                System.out.println("par1: " + parHStart + i * parHStep);
                System.out.println("par2: " + parVStart + j * parVStep);
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setStatusString("exception");
                statusEv.setType(CoreStatusEvent.STRING);
                notifyCoreStatusListeners(statusEv);
                return false;
            }

            // both zero
            if (Math.abs(result[0]) < epsilon && Math.abs(result[1]) < epsilon) {
                color = Color.black.getRGB();
            }
            // one zero one positive
            else if (Math.abs(result[0]) < epsilon && result[1] > 0
                    || Math.abs(result[1]) < epsilon && result[0] > 0) {
                color = Color.red.getRGB();
            }
            // one zero one negative
            else if (Math.abs(result[0]) < epsilon && result[1] < 0
                    || Math.abs(result[1]) < epsilon && result[0] < 0) {
                color = Color.blue.getRGB();
            }
            // one positive one negative
            else if (result[0] < 0 && result[1] > 0 || result[1] < 0 && result[0] > 0) {
                color = Color.green.getRGB();
            }
            // both positive
            else if (result[0] > 0 && result[1] > 0) {
                color = Color.orange.getRGB();
            }
            // both negative
            else if (result[0] < 0 && result[1] < 0) {
                color = Color.pink.getRGB();
            } else { // impossible
                color = Color.yellow.getRGB();
            }

            data[i + j * (int) dataArea.getWidth()] = color;

            if (stopped == true) {
                return false;
            }
            if (j == (int) dataArea.getHeight() - 1) {
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setPercent(0);
                statusEv.setType(CoreStatusEvent.COUNT | CoreStatusEvent.PERCENT);
                notifyCoreStatusListeners(statusEv);
            }
        }
    }

    return true;
}