Example usage for java.awt.image BufferedImage getRGB

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

Introduction

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

Prototype

public int[] getRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) 

Source Link

Document

Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.

Usage

From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java

/**
 * Compare two files, according to parameters passed via command line
 * @param pOne first file to compare/*  ww w  . j a  va2s. co  m*/
 * @param pTwo second file to compare
 * @param pHeatMapImage file to save ssim heat map image to
 * @param pCalcSSIM whether or not to calculate ssim
 * @param pCalcPSNR whether or not to calculate psnr
 */
private static void compare(final File pOne, final File pTwo, final String pHeatMapImage,
        final boolean pCalcSSIM, final boolean pCalcPSNR) {

    //just load the images once and use the internal methods for calculating ssim/psnr
    long time = System.currentTimeMillis();
    BufferedImage imageOne = null;
    try {
        imageOne = Imaging.getBufferedImage(pOne);
    } catch (IOException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    } catch (NullPointerException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    } catch (ImageReadException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    }
    final long oneLoadTime = System.currentTimeMillis() - time;
    //getRGB only returns 8 bits per component, so what about 16-bit images?
    final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0,
            imageOne.getWidth());
    final int width = imageOne.getWidth();
    final int height = imageOne.getHeight();
    final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY
            || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY);
    imageOne = null;
    time = System.currentTimeMillis();
    BufferedImage imageTwo = null;
    try {
        imageTwo = Imaging.getBufferedImage(pTwo);
    } catch (IOException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    } catch (NullPointerException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    } catch (ImageReadException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    }
    final long twoLoadTime = System.currentTimeMillis() - time;

    //getRGB only returns 8 bits per component, so what about 16-bit images?
    final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0,
            imageTwo.getWidth());
    imageTwo = null;

    //calculate psnr if wanted
    time = System.currentTimeMillis();
    double psnr = 0;
    long psnrCalc = 0;
    if (pCalcPSNR) {
        psnr = calcPSNR(oneA, twoA, greyscale);
        psnrCalc = System.currentTimeMillis() - time;
    }

    //calculate ssim if wanted
    time = System.currentTimeMillis();
    List<Double> ssimMin = new LinkedList<Double>();
    List<Double> ssimVariance = new LinkedList<Double>();
    double ssim = 0;
    long ssimCalc = 0;
    if (pCalcSSIM) {
        ssim = calcSSIM(oneA, twoA, width, height, greyscale, pHeatMapImage, ssimMin, ssimVariance);
        ssimCalc = System.currentTimeMillis() - time;
    }

    System.out.println("<dissimilar version=\"" + version + "\">");
    System.out.println("     <file loadTimeMS=\"" + oneLoadTime + "\">" + pOne + "</file>");
    System.out.println("     <file loadTimeMS=\"" + twoLoadTime + "\">" + pTwo + "</file>");
    if (pCalcSSIM) {
        System.out.println("     <ssim calcTimeMS=\"" + ssimCalc + "\">");
        if (ssim > 0) {
            System.out.println("          <mean>" + new DecimalFormat("0.0000000").format(ssim) + "</mean>");
            System.out.println(
                    "          <min>" + new DecimalFormat("0.0000000").format(ssimMin.get(0)) + "</min>");
            System.out.println("          <variance>"
                    + new DecimalFormat("0.0000000").format(ssimVariance.get(0)) + "</variance>");
        } else {
            System.out.println("failed");
        }
        System.out.println("     </ssim>");
    }
    if (pCalcPSNR) {
        System.out.println("     <psnr calcTimeMS=\"" + psnrCalc + "\">"
                + new DecimalFormat("0.0000").format(psnr) + "</psnr>");
    }
    System.out.println("</dissimilar>");

}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

public static BufferedImage resizeNinePatchImage(Project project, ImageInformation information)
        throws IOException {
    BufferedImage image = ImageIO.read(information.getImageFile());
    int originalWidth = image.getWidth();
    int originalHeight = image.getHeight();
    if (originalWidth - 2 == information.getTargetWidth() && originalHeight - 2 == information.getTargetHeight()
            && MathUtils.floatEquals(information.getFactor(), 1f)) {
        return image;
    }/*from   w w  w .j  a  va2s .  co m*/

    int newWidth = information.getTargetWidth();
    int newHeight = information.getTargetHeight();
    if (newWidth <= 0 || newHeight <= 0) {
        newWidth = originalWidth;
        newHeight = originalHeight;
    }

    if (information.getFactor() >= 0) {
        newWidth = (int) (newWidth * information.getFactor());
        newHeight = (int) (newHeight * information.getFactor());
    }

    BufferedImage trimmedImage = trim9PBorder(image);
    ImageInformation trimmedImageInformation = ImageInformation.newBuilder(information)
            .setExportName(getExportName("trimmed", information.getExportName())).build(project);
    saveImageTempFile(trimmedImage, trimmedImageInformation);
    trimmedImage = resizeNormalImage(trimmedImage, newWidth, newHeight, trimmedImageInformation);
    saveImageTempFile(trimmedImage, ImageInformation.newBuilder(trimmedImageInformation)
            .setExportName(getExportName("trimmedResized", information.getExportName())).build(project));

    BufferedImage borderImage;

    int w = trimmedImage.getWidth();
    int h = trimmedImage.getHeight();

    try {
        borderImage = generateBordersImage(image, w, h);
    } catch (Exception e) {
        return null;
    }

    int[] rgbArray = new int[w * h];
    trimmedImage.getRGB(0, 0, w, h, rgbArray, 0, w);
    borderImage.setRGB(1, 1, w, h, rgbArray, 0, w);

    return borderImage;
}

From source file:com.wet.wired.jsr.recorder.ScreenRecorder.java

public void recordFrame() throws IOException {
    long t1 = System.currentTimeMillis();
    BufferedImage bImage = captureScreen(recordArea);
    frameTime = System.currentTimeMillis() - startTime;
    long t2 = System.currentTimeMillis();

    rawData = new int[frameSize];

    bImage.getRGB(0, 0, recordArea.width, recordArea.height, rawData, 0, recordArea.width);
    long t3 = System.currentTimeMillis();

    streamPacker.packToStream(new DataPack(rawData, frameTime));

    logger.trace("recordArea.width");
    logger.trace("capture time:" + (t2 - t1));
    logger.trace("data grab time:" + (t3 - t2));

    listener.frameRecorded(false);/*from w  w w  .  j  a v  a2 s  .  c  o  m*/
}

From source file:com.bwc.ora.models.Lrp.java

/**
 * Get an array containing the gray scale values of the LRP arranged from
 * smallest y-value to greatest y-value (i.e. top to bottom in the image).
 * The pixel data is taken from the transformed OCT with all appropriately
 * applied transformations. Each call to this method will go and grab the
 * pixel data allowing for updated intensity data to be grabbed immediately.
 *
 * @return//from  w  w w  . j a  v  a  2  s  .c  om
 */
private int[] getIntensityValues() {

    BufferedImage octToProcess = transformedOctImage == null ? oct.getTransformedOct() : transformedOctImage;
    int[] rgbArray = octToProcess.getRGB(x, y, width, height, null, 0, width);

    return IntStream.range(0, height)
            .map(scanY -> (int) Math.round(Arrays.stream(rgbArray, width * scanY, width * (scanY + 1))
                    .map(ImageUtils::calculateGrayScaleValue).average().orElse(0)))
            .toArray();
}

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

public static void copyRGBcolumns(BufferedImage sourceImg, int sourceStartX, int sourceWidth,
        BufferedImage targetImg, int targetStartX) {
    targetImg.setRGB(targetStartX, 0, sourceWidth, sourceImg.getHeight(),
            sourceImg.getRGB(sourceStartX, 0, sourceWidth, sourceImg.getHeight(), null, 0, sourceWidth), 0,
            sourceWidth);//from  w  w w .j av a2  s  .  co  m
}

From source file:com.neophob.sematrix.core.generator.Image.java

/**
 * load a new file.//from  www. ja v  a 2s  .  c  o  m
 *
 * @param filename the filename
 */
public synchronized void loadFile(String filename) {
    if (StringUtils.isBlank(filename)) {
        LOG.log(Level.INFO, "Empty filename provided, call ignored!");
        return;
    }

    //only load if needed
    if (StringUtils.equals(filename, this.filename)) {
        LOG.log(Level.INFO, "new filename does not differ from old: " + filename);
        return;
    }

    try {
        String fileToLoad = fileUtils.getImageDir() + File.separator + filename;

        LOG.log(Level.INFO, "load image " + fileToLoad);
        BufferedImage img = ImageIO.read(new File(fileToLoad));
        if (img == null || img.getHeight() < 2) {
            LOG.log(Level.WARNING, "Invalid image, image height is < 2!");
            return;
        }

        //convert to RGB colorspace
        int w = img.getWidth();
        int h = img.getHeight();
        int[] dataBuffInt = img.getRGB(0, 0, w, h, null, 0, w);

        LOG.log(Level.INFO, "resize to img " + filename + " " + internalBufferXSize + ", " + internalBufferYSize
                + " using " + resize.getName());
        this.internalBuffer = resize.getBuffer(dataBuffInt, internalBufferXSize, internalBufferYSize, w, h);
        this.filename = filename;

        short r, g, b;
        int rgbColor;

        //greyscale it
        for (int i = 0; i < internalBuffer.length; i++) {
            rgbColor = internalBuffer[i];
            r = (short) ((rgbColor >> 16) & 255);
            g = (short) ((rgbColor >> 8) & 255);
            b = (short) (rgbColor & 255);
            int val = (int) (r * 0.3f + g * 0.59f + b * 0.11f);
            internalBuffer[i] = val;
        }

    } catch (Exception e) {
        LOG.log(Level.WARNING, "Failed to load image " + filename, e);
    }
}

From source file:com.softenido.cafedark.image.hash.ImageHashBuilder.java

public Hash buildHash(BufferedImage image) {
    count.incrementAndGet();/*from   www  .  j ava  2  s .c o  m*/
    image = scale.filter(image);

    int w = image.getWidth();
    int h = image.getHeight();

    //        JFrame frame = new JFrame();
    //        frame.setTitle("["+w+"x"+h+"]"+" ");
    //        frame.add(new JLabel(new ImageIcon(image)));
    //        frame.setVisible(true);
    //        frame.pack();

    int[] pixels = null;
    pixels = image.getRGB(0, 0, w, h, pixels, 0, w);
    if (colorThreshold > 0 && gray) {
        byte[] hash = new byte[pixels.length];
        for (int i = 0; i < hash.length; i++) {
            hash[i] = (byte) (pixels[i] & 0xff);
        }
        int hc = (w * h) + (w - h);
        //            System.out.println(Arrays.toString(hash));
        return new StickyImageHash(w, h, hc, hash, colorThreshold, countThresold);
    }
    if (colorThreshold > 0) {
        byte[] hash = ArrayUtils.getByteArray(pixels);
        int hc = (w * h) + (w - h);
        System.out.println(Arrays.toString(hash));
        return new StickyImageHash(w, h, hc, hash, colorThreshold, countThresold);
    }
    byte[] hash = buildDigest(pixels);
    int hc = (w * h) + (w - h) + Arrays.hashCode(hash);
    System.out.println(Arrays.toString(hash));
    return new ImageHash(w, h, hc, hash);
}

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

public static void copyRGB(BufferedImage sourceImg, int sourceStartX, int sourceStartY, int sourceWidth,
        int sourceHeight, BufferedImage targetImg, int targetStartX, int targetStartY) {
    targetImg.setRGB(targetStartX, targetStartY, sourceWidth, sourceHeight,
            sourceImg.getRGB(sourceStartX, sourceStartY, sourceWidth, sourceHeight, null, 0, sourceWidth), 0,
            sourceWidth);//from   w  ww .j a  va  2s .c  o m
}

From source file:ImageOpByRomain.java

/**
 * <p>//from  w  w w.j av a  2s . c  om
 * 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:GifEncoder.java

public void encode(BufferedImage bufferedimage, DataOutputStream dataoutputstream, Hashtable hashtable)
        throws Exception {
    try {/*from  w ww  .j a  va2s .com*/
        a = bufferedimage.getWidth();
        g = bufferedimage.getHeight();
        e = bufferedimage.getRGB(0, 0, a, g, null, 0, a);
        int i4 = 0;
        b = hashtable.get("encoding").toString();
        if (b.equals("websafe")) {
            int ai[] = new int[256];
            i = new int[256];
            h = 8;
            int k1 = 0;
            int j;
            int j1 = j = 0;
            for (; j <= 255; j += 51) {
                for (int l = 0; l <= 255; l += 51) {
                    for (int i1 = 0; i1 <= 255;) {
                        i[j1] = (j << 16) + (l << 8) + i1;
                        ai[k1++] = j1;
                        i1 += 51;
                        j1++;
                    }

                }

            }

            if (f > 0) {
                int j4 = c[0];
                int l1 = ((c[0] >> 16 & 0xff) + 25) / 51;
                int k2 = ((c[0] >> 8 & 0xff) + 25) / 51;
                int j3 = ((c[0] & 0xff) + 25) / 51;
                i4 = l1 * 36 + k2 * 6 + j3;
                for (j = 1; j < f; j++) {
                    int i2 = ((c[j] >> 16 & 0xff) + 25) / 51;
                    int l2 = ((c[j] >> 8 & 0xff) + 25) / 51;
                    int k3 = ((c[j] & 0xff) + 25) / 51;
                    ai[i2 * 36 + l2 * 6 + k3] = i4;
                }

            }
            j = 0;
            try {
                do {
                    int i5 = e[j];
                    int j2 = ((i5 >> 16 & 0xff) + 25) / 51;
                    int i3 = ((i5 >> 8 & 0xff) + 25) / 51;
                    int l3 = ((i5 & 0xff) + 25) / 51;
                    e[j++] = ai[j2 * 36 + i3 * 6 + l3];
                } while (true);
            } catch (Exception exception1) {
            }
        }
        /*else
        if(b.equals("optimized"))
        {
        try
        {
            int k4 = Integer.parseInt(hashtable.get("colors").toString());
            for(h = 1; k4 - 1 >> h > 0; h++) { }
            i = new int[1 << h];
            CSelectiveQuant cselectivequant = new CSelectiveQuant();
            for(int j5 = 0; j5 < e.length; j5++)
            {
                cselectivequant.addPixel(e[j5]);
            }
                
            boolean flag = f > 0;
            int k5 = flag ? 1 : 0;
            int ai1[] = cselectivequant.createPalette(k4 - k5);
            for(int l5 = 0; l5 < i.length; l5++)
            {
                try
                {
                    i[l5] = ai1[l5 - k5];
                }
                catch(ArrayIndexOutOfBoundsException arrayindexoutofboundsexception)
                {
                    i[l5] = 0;
                }
            }
                
            if(flag)
            {
                i4 = 0;
                for(int i6 = 0; i6 < f; i6++)
                {
                    cselectivequant.setIndex(c[i6], -1);
                }
                
            }
            for(int j6 = 0; j6 < e.length; j6++)
            {
                e[j6] = cselectivequant.getIndex(e[j6]) + k5;
            }
                
        }
        catch(NumberFormatException numberformatexception)
        {
            CmsLogger.logInfo("Parameter: 'colors' is malformated...");
            return;
        }
        }
        */
        dataoutputstream.write("GIF89a".getBytes());
        dataoutputstream.writeByte(a);
        dataoutputstream.writeByte(a >> 8);
        dataoutputstream.writeByte(g);
        dataoutputstream.writeByte(g >> 8);
        dataoutputstream.writeByte(0xf0 | h - 1);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(0);
        int k = 0;
        try {
            do {
                int l4 = i[k++];
                dataoutputstream.writeByte(l4 >> 16 & 0xff);
                dataoutputstream.writeByte(l4 >> 8 & 0xff);
                dataoutputstream.writeByte(l4 & 0xff);
            } while (true);
        } catch (Exception exception) {
        }
        if (f > 0) {
            dataoutputstream.writeByte(33);
            dataoutputstream.writeByte(249);
            dataoutputstream.writeByte(4);
            dataoutputstream.writeByte(1);
            dataoutputstream.writeByte(0);
            dataoutputstream.writeByte(0);
            dataoutputstream.writeByte(i4);
            dataoutputstream.writeByte(0);
        }
        dataoutputstream.writeByte(44);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(a);
        dataoutputstream.writeByte(a >> 8);
        dataoutputstream.writeByte(g);
        dataoutputstream.writeByte(g >> 8);
        dataoutputstream.writeByte(0);
        dataoutputstream.writeByte(h);
        a(e, h, dataoutputstream);
        dataoutputstream.writeByte(59);
        dataoutputstream.flush();
        return;
    } catch (Exception e) {
    }
}