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:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java

private byte[] getPixelsFromMaskFiles(List<String> maskFilePaths, List<String> dicomFilePaths,
        boolean removeEmpty) throws FileNotFoundException, IOException, DicomException {
    byte[] pixels = null;
    List<Integer> emptyFileIndex = new ArrayList<Integer>();
    for (int i = 0; i < maskFilePaths.size(); i++) {
        File maskFile = new File(maskFilePaths.get(i));
        BufferedImage maskImage = ImageIO.read(maskFile);
        // BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(),
        // BufferedImage.TYPE_BYTE_BINARY);
        byte[] new_frame = ((DataBufferByte) maskImage.getRaster().getDataBuffer()).getData();
        byte[] pixel_data = new_frame;
        long rgbLen = maskImage.getWidth() * maskImage.getHeight() * 4;
        long bwLen = maskImage.getWidth() * maskImage.getHeight() / 8;
        long greyLen = maskImage.getWidth() * maskImage.getHeight();
        if (i == 0) {
            System.out.println("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen
                    + " Actual tiff data len:" + new_frame.length);
            log.info("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen
                    + " Actual tiff data len:" + new_frame.length);
        }/*from  www .  j  a  va 2s .  c  om*/
        boolean nonzerodata = false;

        // looks like 4 bytes/pixel, compress to 1 bit/pixel (else assume it is already 1 bit/pixel)
        if (new_frame.length == rgbLen) {
            if (i % 10 == 0) {
                System.out.println("Compressing tiff mask from rgb, mask:" + i);
                log.debug("Compressing tiff mask from rgb, mask:" + i);
            }

            int numpixels = new_frame.length / 4;
            int numbytes = numpixels / 8;
            pixel_data = new byte[numbytes];
            for (int k = 0; k < numbytes; k++) {
                int index = k * 8 * 4;
                pixel_data[k] = 0;
                for (int l = 0; l < 4 * 8; l = l + 4) {
                    if (new_frame[index + l] != 0) {
                        int setBit = pixel_data[k] + (1 << (l / 4));
                        pixel_data[k] = (byte) setBit;
                        nonzerodata = true;
                    }
                }
                if (pixel_data[k] != 0)
                    log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " compress rgb");
            }

            //            

        }
        // ml if 
        else if (new_frame.length == greyLen || maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
            if (maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { //if not indexed old version should work
                if (i % 10 == 0) {
                    System.out.println("indexed tiff mask from rgb, mask:" + i);
                    log.debug("indexed tiff mask from rgb, mask:" + i);
                }

                //            pixel_data = ((DataBufferByte)convertRGBAToIndexed(maskImage).getRaster().getDataBuffer()).getData();
                int numpixels = new_frame.length;
                pixel_data = new byte[numpixels];
                log.info("maskfile data");
                for (int k = 0; k < numpixels; k++) {
                    pixel_data[k] = 0;
                    if (new_frame[k] != 0) {
                        pixel_data[k] = new_frame[k];
                        nonzerodata = true;
                    }

                    //               byte red = (byte)((new_frame[index] * 8) / 256);
                    //               byte green = (byte)((new_frame[index+1] * 8) / 256);
                    //               byte blue = (byte)((new_frame[index+2] * 4) / 256);
                    //               pixel_data[k] =(byte) ((red << 5) | (green << 2) | blue);

                    //               for (int l = 0; l < 4; l=l+4)
                    //               {
                    //                  if (new_frame[index + l] != 0)
                    //                  {
                    //                     int setBit =  pixel_data[k] + (1 << (l));
                    //                     pixel_data[k] =(byte) setBit;
                    //                     nonzerodata = true;
                    //                  }
                    //               }
                    if (pixel_data[k] != 0)
                        log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " rgb ");
                }

            } else {
                if (i % 10 == 0) {
                    System.out.println("Compressing tiff mask from grey, mask:" + i);
                    log.debug("Compressing tiff mask from grey, mask:" + i);
                }
                int numpixels = new_frame.length;
                int numbytes = numpixels / 8;
                pixel_data = new byte[numbytes];
                for (int k = 0; k < numbytes; k++) {
                    int index = k * 8;
                    pixel_data[k] = 0;
                    for (int l = 0; l < 8; l++) {
                        if (new_frame[index + l] != 0) {
                            int setBit = pixel_data[k] + (1 << l);
                            pixel_data[k] = (byte) setBit;
                            nonzerodata = true;
                        }
                    }
                    if (pixel_data[k] != 0)
                        log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k]);
                }
            }

        } else //bw
        {
            if (i % 10 == 0) {
                System.out.println("Flipping odd bytes of bw tif, mask:" + i);
                log.debug("Flipping odd bytes of bw tif, mask:" + i);
            }
            int numbytes = maskImage.getWidth() * maskImage.getHeight() / 8;
            pixel_data = new byte[numbytes];
            for (int k = 0; k < numbytes; k++) {
                // Flip every odd byte. why on earth do we need to do this?
                if (new_frame[k] != 0)
                    nonzerodata = true;
                //flip if not indexed image (8 bit color)
                if (k % 2 != 0 && new_frame[k] != 0) {
                    pixel_data[k] = 0;
                    if ((new_frame[k] & 1) == 1) {
                        int setBit = pixel_data[k] + 128;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 2) == 2) {
                        int setBit = pixel_data[k] + 64;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 4) == 4) {
                        int setBit = pixel_data[k] + 32;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 8) == 8) {
                        int setBit = pixel_data[k] + 16;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 16) == 16) {
                        int setBit = pixel_data[k] + 8;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 32) == 32) {
                        int setBit = pixel_data[k] + 4;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 64) == 64) {
                        int setBit = pixel_data[k] + 2;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 128) == 128) {
                        int setBit = pixel_data[k] + 1;
                        pixel_data[k] = (byte) setBit;
                    }
                    if (new_frame[k] != 0)
                        System.out.println("Old byte:" + new_frame[k] + " New byte:" + pixel_data[k]);
                } else
                    pixel_data[k] = new_frame[k];
                if (pixel_data[k] != 0)
                    log.info("maskfile bw-rgb" + i + ": " + k + " pixel:" + pixel_data[k]);
            }
        }
        log.info("maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length
                + " nonzero data:" + nonzerodata);
        if (!nonzerodata && removeEmpty) {
            log.debug("Nodata - maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:"
                    + pixel_data.length);
            emptyFileIndex.add(i);
            continue;
        }
        if (pixels == null) {
            //pixels = new_frame.clone();
            pixels = pixel_data;
        } else {
            byte[] temp = new byte[pixels.length + pixel_data.length];
            System.arraycopy(pixels, 0, temp, 0, pixels.length);
            System.arraycopy(pixel_data, 0, temp, pixels.length, pixel_data.length);
            //pixels = temp.clone();
            pixels = temp;
        }
    }
    for (int i = 0; i < emptyFileIndex.size(); i++) {
        int index = emptyFileIndex.get(i);
        log.info("Removing dicom " + (dicomAttributes.length - index - 1));
        dicomFilePaths.remove(dicomAttributes.length - index - 1);
        dicomAttributes[index] = null;
    }
    //      for (int i = 0; i < emptyFileIndex.size(); i++)
    //      {
    //         int index = emptyFileIndex.get(i);
    //         log.info("Removing dicom " + (maskFilePaths.size() - index - 1));
    //         dicomFilePaths.remove(maskFilePaths.size() - index - 1); // DicomFiles are in reverse order for!!!
    //      }
    if (pixels == null)
        throw new RuntimeException("The DSO has all empty frames");
    log.info("Number of pixels:" + pixels.length + " dicoms:" + dicomFilePaths.size());
    return pixels;
}

From source file:org.csa.rstb.dat.toolviews.HaAlphaPlotPanel.java

@Override
protected void updateChartData() {

    final RasterDataNode rasterX = getRaster(X_VAR);
    final RasterDataNode rasterY = getRaster(Y_VAR);

    if (rasterX == null || rasterY == null) {
        return;/*from  w  w w  .  j av a2s. co  m*/
    }

    ProgressMonitorSwingWorker<BufferedImage, Object> swingWorker = new ProgressMonitorSwingWorker<BufferedImage, Object>(
            this, "Computing plot") {

        @Override
        protected BufferedImage doInBackground(ProgressMonitor pm) throws Exception {
            pm.beginTask("Computing plot...", 100);
            try {
                checkBandsForRange();
                setRange(X_VAR, rasterX, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null,
                        SubProgressMonitor.create(pm, 15));
                setRange(Y_VAR, rasterY, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null,
                        SubProgressMonitor.create(pm, 15));
                BufferedImage densityPlotImage = ProductUtils.createDensityPlotImage(rasterX,
                        axisRangeControls[X_VAR].getMin().floatValue(),
                        axisRangeControls[X_VAR].getMax().floatValue(), rasterY,
                        axisRangeControls[Y_VAR].getMin().floatValue(),
                        axisRangeControls[Y_VAR].getMax().floatValue(),
                        dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, 512, 512,
                        backgroundColor, null, SubProgressMonitor.create(pm, 70));

                densityPlotImage = new BufferedImage(untoggledColorModel, densityPlotImage.getRaster(),
                        densityPlotImage.isAlphaPremultiplied(), null);

                plotColorsInverted = false;
                return densityPlotImage;
            } finally {
                pm.done();
            }
        }

        @Override
        public void done() {
            try {
                checkBandsForRange();
                final BufferedImage densityPlotImage = get();
                double minX = axisRangeControls[X_VAR].getMin();
                double maxX = axisRangeControls[X_VAR].getMax();
                double minY = axisRangeControls[Y_VAR].getMin();
                double maxY = axisRangeControls[Y_VAR].getMax();
                if (minX > maxX || minY > maxY) {
                    JOptionPane.showMessageDialog(getParentDialogContentPane(),
                            "Failed to compute plot.\n" + "No Pixels considered..",
                            /*I18N*/
                            CHART_TITLE, /*I18N*/
                            JOptionPane.ERROR_MESSAGE);
                    plot.setDataset(null);
                    return;

                }

                if (MathUtils.equalValues(minX, maxX, 1.0e-4)) {
                    minX = Math.floor(minX);
                    maxX = Math.ceil(maxX);
                }
                if (MathUtils.equalValues(minY, maxY, 1.0e-4)) {
                    minY = Math.floor(minY);
                    maxY = Math.ceil(maxY);
                }
                plot.setImage(densityPlotImage);
                plot.setImageDataBounds(new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY));
                axisRangeControls[X_VAR].adjustComponents(minX, maxX, NUM_DECIMALS);
                axisRangeControls[Y_VAR].adjustComponents(minY, maxY, NUM_DECIMALS);
                //                    plot.getDomainAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(X_VAR), "Entropy", false));
                //                    plot.getRangeAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(Y_VAR), "Alpha", false));
                plot.getDomainAxis().setLabel("Entropy");
                plot.getRangeAxis().setLabel("Alpha");
                toggleZoneOverlayCheckBox.setEnabled(true);

                // clear the list
                java.util.List<XYAnnotation> annotList = plot.getAnnotations();
                for (XYAnnotation an : annotList) {
                    plot.removeAnnotation(an);
                }

                if (toggleZoneOverlayCheckBox.isSelected()) {
                    drawZoneOverlay();
                }

            } catch (InterruptedException | CancellationException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute plot.\n" + "Calculation canceled.",
                        /*I18N*/
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            } catch (ExecutionException | IllegalArgumentException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute plot.\n" + "An error occurred:\n" + e.getCause().getMessage(),
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    };
    swingWorker.execute();
}

From source file:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java

/**
 * get pixels and fill firstFrame for dso
 * @param maskFilePaths/*  ww  w .  j  a v a  2  s.c  om*/
 * @param dicomFilePaths
 * @param removeEmpty
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DicomException
 */
private byte[] getPixelsFromMaskFiles(List<String> maskFilePaths, List<String> dicomFilePaths,
        boolean removeEmpty, String dsoUID) throws FileNotFoundException, IOException, DicomException {
    Integer firstFrame = -1;
    byte[] pixels = null;
    List<Integer> emptyFileIndex = new ArrayList<Integer>();
    for (int i = 0; i < maskFilePaths.size(); i++) {
        File maskFile = new File(maskFilePaths.get(i));
        BufferedImage maskImage = ImageIO.read(maskFile);
        // BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(),
        // BufferedImage.TYPE_BYTE_BINARY);
        byte[] new_frame = ((DataBufferByte) maskImage.getRaster().getDataBuffer()).getData();
        byte[] pixel_data = new_frame;
        long rgbLen = maskImage.getWidth() * maskImage.getHeight() * 4;
        long bwLen = maskImage.getWidth() * maskImage.getHeight() / 8;
        long greyLen = maskImage.getWidth() * maskImage.getHeight();
        if (i == 0) {
            System.out.println("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen
                    + " Actual tiff data len:" + new_frame.length);
            log.info("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen
                    + " Actual tiff data len:" + new_frame.length);
        }
        boolean nonzerodata = false;

        // looks like 4 bytes/pixel, compress to 1 bit/pixel (else assume it is already 1 bit/pixel)
        if (new_frame.length == rgbLen) {
            if (i % 10 == 0) {
                System.out.println("Compressing tiff mask from rgb, mask:" + i);
                log.debug("Compressing tiff mask from rgb, mask:" + i);
            }

            int numpixels = new_frame.length / 4;
            int numbytes = numpixels / 8;
            pixel_data = new byte[numbytes];
            for (int k = 0; k < numbytes; k++) {
                int index = k * 8 * 4;
                pixel_data[k] = 0;
                for (int l = 0; l < 4 * 8; l = l + 4) {
                    if (new_frame[index + l] != 0) {
                        int setBit = pixel_data[k] + (1 << (l / 4));
                        pixel_data[k] = (byte) setBit;
                        nonzerodata = true;
                    }
                }
                if (pixel_data[k] != 0)
                    log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " compress rgb");
            }

            //            

        }
        // ml if 
        else if (new_frame.length == greyLen || maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
            if (maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { //if not indexed old version should work
                if (i % 10 == 0) {
                    System.out.println("indexed tiff mask from rgb, mask:" + i);
                    log.debug("indexed tiff mask from rgb, mask:" + i);
                }

                //            pixel_data = ((DataBufferByte)convertRGBAToIndexed(maskImage).getRaster().getDataBuffer()).getData();
                int numpixels = new_frame.length;
                pixel_data = new byte[numpixels];
                log.info("maskfile data");
                for (int k = 0; k < numpixels; k++) {
                    pixel_data[k] = 0;
                    if (new_frame[k] != 0) {
                        pixel_data[k] = new_frame[k];
                        nonzerodata = true;
                    }

                    //               byte red = (byte)((new_frame[index] * 8) / 256);
                    //               byte green = (byte)((new_frame[index+1] * 8) / 256);
                    //               byte blue = (byte)((new_frame[index+2] * 4) / 256);
                    //               pixel_data[k] =(byte) ((red << 5) | (green << 2) | blue);

                    //               for (int l = 0; l < 4; l=l+4)
                    //               {
                    //                  if (new_frame[index + l] != 0)
                    //                  {
                    //                     int setBit =  pixel_data[k] + (1 << (l));
                    //                     pixel_data[k] =(byte) setBit;
                    //                     nonzerodata = true;
                    //                  }
                    //               }
                    if (pixel_data[k] != 0)
                        log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " rgb ");
                }

            } else {
                if (i % 10 == 0) {
                    System.out.println("Compressing tiff mask from grey, mask:" + i);
                    log.debug("Compressing tiff mask from grey, mask:" + i);
                }
                int numpixels = new_frame.length;
                int numbytes = numpixels / 8;
                pixel_data = new byte[numbytes];
                for (int k = 0; k < numbytes; k++) {
                    int index = k * 8;
                    pixel_data[k] = 0;
                    for (int l = 0; l < 8; l++) {
                        if (new_frame[index + l] != 0) {
                            int setBit = pixel_data[k] + (1 << l);
                            pixel_data[k] = (byte) setBit;
                            nonzerodata = true;
                        }
                    }
                    if (pixel_data[k] != 0)
                        log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k]);
                }
            }

        } else //bw
        {
            if (i % 10 == 0) {
                System.out.println("Flipping odd bytes of bw tif, mask:" + i);
                log.debug("Flipping odd bytes of bw tif, mask:" + i);
            }
            int numbytes = maskImage.getWidth() * maskImage.getHeight() / 8;
            pixel_data = new byte[numbytes];
            for (int k = 0; k < numbytes; k++) {
                // Flip every odd byte. why on earth do we need to do this?
                if (new_frame[k] != 0)
                    nonzerodata = true;
                //flip if not indexed image (8 bit color)
                if (k % 2 != 0 && new_frame[k] != 0) {
                    pixel_data[k] = 0;
                    if ((new_frame[k] & 1) == 1) {
                        int setBit = pixel_data[k] + 128;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 2) == 2) {
                        int setBit = pixel_data[k] + 64;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 4) == 4) {
                        int setBit = pixel_data[k] + 32;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 8) == 8) {
                        int setBit = pixel_data[k] + 16;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 16) == 16) {
                        int setBit = pixel_data[k] + 8;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 32) == 32) {
                        int setBit = pixel_data[k] + 4;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 64) == 64) {
                        int setBit = pixel_data[k] + 2;
                        pixel_data[k] = (byte) setBit;
                    }
                    if ((new_frame[k] & 128) == 128) {
                        int setBit = pixel_data[k] + 1;
                        pixel_data[k] = (byte) setBit;
                    }
                    if (new_frame[k] != 0)
                        System.out.println("Old byte:" + new_frame[k] + " New byte:" + pixel_data[k]);
                } else
                    pixel_data[k] = new_frame[k];
                if (pixel_data[k] != 0)
                    log.info("maskfile bw-rgb" + i + ": " + k + " pixel:" + pixel_data[k]);
            }
        }
        log.info("maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length
                + " nonzero data:" + nonzerodata);
        if (!nonzerodata && removeEmpty) {
            log.debug("Nodata - maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:"
                    + pixel_data.length);
            emptyFileIndex.add(i);
            continue;
        }
        if (nonzerodata) {
            Integer reverseNum = maskFilePaths.size() - i - 1;
            if (firstFrame == -1 || reverseNum < firstFrame) {
                firstFrame = reverseNum;
                log.info("setting firstframe:" + firstFrame);

            }

        }
        if (pixels == null) {
            //pixels = new_frame.clone();
            pixels = pixel_data;
        } else {
            byte[] temp = new byte[pixels.length + pixel_data.length];
            System.arraycopy(pixels, 0, temp, 0, pixels.length);
            System.arraycopy(pixel_data, 0, temp, pixels.length, pixel_data.length);
            //pixels = temp.clone();
            pixels = temp;
        }
    }
    //update the firstframe for this dso
    log.info("first frame for dso:" + dsoUID + " is " + firstFrame);
    firstFrames.put(dsoUID, firstFrame);
    for (int i = 0; i < emptyFileIndex.size(); i++) {
        int index = emptyFileIndex.get(i);
        log.info("Removing dicom " + (dicomAttributes.length - index - 1));
        dicomFilePaths.remove(dicomAttributes.length - index - 1);
        dicomAttributes[index] = null;
    }
    //      for (int i = 0; i < emptyFileIndex.size(); i++)
    //      {
    //         int index = emptyFileIndex.get(i);
    //         log.info("Removing dicom " + (maskFilePaths.size() - index - 1));
    //         dicomFilePaths.remove(maskFilePaths.size() - index - 1); // DicomFiles are in reverse order for!!!
    //      }
    if (pixels == null)
        throw new RuntimeException("The DSO has all empty frames");
    log.info("Number of pixels:" + pixels.length + " dicoms:" + dicomFilePaths.size());
    return pixels;
}

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

/**
 * Performs a lookup against an internal raster. The sampling is actually done against 4 pixels,
 * idx should already have been modified to use one level higher than strictly necessary.
 * //from   w w w . j  a v a  2  s .c o m
 * @param grid
 * @param idx
 * @return
 */
private boolean lookupQuad(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
    int baseX = (int) (idx[0] - gridCoverage[0]);
    int baseY = (int) (gridCoverage[3] - idx[1]);

    int width = mat.getWidth();
    int height = mat.getHeight();

    int x = baseX;
    int y = baseY;

    // We're checking 4 samples. The base is bottom left hand corner
    boolean hasData = false;

    // BL, BR, TL, TR
    int[] xOffsets = { 0, 1, 0, 1 };
    int[] yOffsets = { 0, 0, 1, 1 };

    // Lock, in case someone wants to replace the matrix
    synchronized (mat) {
        try {
            for (int i = 0; i < 4 && !hasData; i++) {
                x = baseX + xOffsets[i];
                y = baseY - yOffsets[i];

                if (x > -1 && x < width && y > -1 && y < height) {
                    if (mat.getRaster().getSample(x, y, 0) == 0) {
                        hasData = true;
                    }
                }
            }
        } catch (ArrayIndexOutOfBoundsException aioob) {
            log.error("x:" + x + "  y:" + y + " (" + mat.getWidth() + " " + mat.getHeight() + ")");
        }
    }

    return hasData;
}

From source file:org.eclipse.birt.chart.device.g2d.G2dRendererBase.java

protected java.awt.Image createImageFromModel(Fill imageModel) throws ChartException {

    java.awt.Image img = null;/*from ww w  .  j a  va  2 s .  c o  m*/
    if (imageModel instanceof EmbeddedImage) {
        try {
            byte[] data = Base64.decodeBase64(((EmbeddedImage) imageModel).getData().getBytes());

            img = createImage(data);
        } catch (Exception ilex) {
            throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex);
        }
    } else if (imageModel instanceof PatternImage) {
        PatternImage pi = (PatternImage) imageModel;
        byte[] data = PatternImageUtil.createImageData(pi, ByteColorModel.RGBA);
        BufferedImage bimg = new BufferedImage(8, 8, BufferedImage.TYPE_4BYTE_ABGR);
        img = bimg;
        WritableRaster raster = bimg.getRaster();
        raster.setDataElements(0, 0, 8, 8, data);
        bimg.flush();
    } else if (imageModel instanceof org.eclipse.birt.chart.model.attribute.Image) {
        if (((org.eclipse.birt.chart.model.attribute.Image) imageModel).getSource() == ImageSourceType.STATIC) {
            try {
                final String sUrl = ((org.eclipse.birt.chart.model.attribute.Image) imageModel).getURL();
                img = (java.awt.Image) _ids.loadImage(SecurityUtil.newURL(sUrl));
            } catch (ChartException ilex) {
                throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex);
            } catch (MalformedURLException muex) {
                throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, muex);
            }
        }
    }

    return img;

}

From source file:org.apache.cocoon.reading.RepoImageReader.java

/**
 * @return the time the read source was last modified or 0 if it is not
 *         possible to detect/*from   w  ww. j  a v  a2 s.co m*/
 */
/*
public long getLastModified() {
if (hasRanges()) {
    // This is a byte range request so we can't use the cache, return null.
    return 0;
}
        
if (quickTest) {
    return inputSource.getLastModified();
}
        
final String systemId = (String) documents.get(request.getRequestURI());
// Note: getURI() might be null in some incomplete implementations
final String sourceURI = inputSource.getURI();
if (systemId == null || (sourceURI != null && sourceURI.equals(systemId))) {
    return inputSource.getLastModified();
}
        
documents.remove(request.getRequestURI());
return 0;
}*/

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {

    if (inputStream != null) {
        if (hasTransform()) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                        + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
            }

            try {
                byte content[] = readFully(inputStream);
                ImageIcon icon = new ImageIcon(content);
                BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                        BufferedImage.TYPE_INT_RGB);
                BufferedImage currentImage = original;
                currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

                if (width > 0 || height > 0) {
                    double ow = icon.getImage().getWidth(null);
                    double oh = icon.getImage().getHeight(null);

                    if (usePercent) {
                        if (width > 0) {
                            width = Math.round((int) (ow * width) / 100);
                        }
                        if (height > 0) {
                            height = Math.round((int) (oh * height) / 100);
                        }
                    }

                    AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                            AffineTransformOp.TYPE_BILINEAR);
                    WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                    filter.filter(currentImage.getRaster(), scaledRaster);

                    currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
                }

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);

                out.flush();
            } catch (ImageFormatException e) {
                throw new ProcessingException(
                        "Error reading the image. " + "Note that only JPEG images are currently supported.");
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }
        } else {
            try {
                InputStream is = inputStream;

                long expires = parameters.getParameterAsInteger("expires", -1);
                if (expires > 0) {
                    response.setDateHeader("Expires", System.currentTimeMillis() + expires);
                }
                response.setHeader("Accept-Ranges", "bytes");

                byte[] buffer = new byte[8192];
                int length;
                while ((length = is.read(buffer)) > -1) {
                    out.write(buffer, 0, length);
                }
                is.close();
                out.flush();
            } catch (RuntimeException e) {
                throw e;
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }

        }
    } else {
        throw new IOException("Deals: Problem, resource not found or Repository not working correctly");
    }

}

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

public static BufferedImage combineRGBA(BufferedImage[] inImgs) {
    BufferedImage out = null;
    int numBands = 0;
    int width = 0;
    int height = 0;
    if (inImgs == null) {
        return null;
    }/*from ww w .  ja  v  a 2  s . c  o  m*/

    if (inImgs.length != 4 && inImgs.length != 3) {
        return null;
    }

    if (inImgs.length == 3) {
        numBands = 3;
    } else if (inImgs.length == 4) {
        if (inImgs[3] == null) {
            numBands = 3;
        } else {
            numBands = 4;
        }
    }

    for (int i = 0; i < numBands; i++) {
        if (inImgs[i] == null) {
            return null;
        }
    }

    //check if all images are the same size
    width = inImgs[0].getWidth();
    height = inImgs[0].getHeight();
    for (int i = 1; i < numBands; i++) {
        if (inImgs[i].getWidth() != width || inImgs[i].getHeight() != height) {
            return null;
        }
    }

    //create output image
    if (numBands == 3) {
        out = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    } else {
        out = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    }

    //set pixels
    WritableRaster outRaster = out.getRaster();

    WritableRaster[] inRasters = new WritableRaster[numBands];
    for (int i = 0; i < numBands; i++) {
        inRasters[i] = inImgs[i].getRaster();
    }

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            for (int i = 0; i < numBands; i++) {
                outRaster.setSample(x, y, i, inRasters[i].getSample(x, y, 0));
            }
        }
    }
    return out;
}

From source file:pl.dp.bz.poid.fouriertest.FourierProc.java

/**
 * Zwraca nam tablic z wartociami pikseli obrazka
 *
 * @return//from   w ww  . jav  a  2s.  c o m
 */
public BufferedImage getInverseFourierImage() {
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, image.getType());
    double[][] tab = new double[fourierImage.length][fourierImage[0].length];
    for (int x = 0; x < fourierImage.length; x++) {
        for (int y = 0; y < fourierImage[x].length; y++) {
            tab[x][y] = fourierImage[x][y].getReal();
        }
    }
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            int[] t = new int[1];
            //                System.out.println("ZESP: "+inverseImage[x][y]);
            double value = tab[x][y];
            //                double value = (Math.log(inverseImage[x][y]+1.0))*(255.0/Math.log(max + 1));
            //                System.out.println("VALUE: "+value);
            int v;
            if (value > 255) {
                v = 255;
            } else if (value < 0) {
                v = 0;
            } else {
                v = (int) value;
            }
            //                System.out.println("V: "+v);
            t[0] = v;
            bufferedImage.getRaster().setPixel(x, y, t);
        }
    }

    return bufferedImage;
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

private static BufferedImage fromAny(PDImage pdImage, WritableRaster raster, COSArray colorKey)
        throws IOException {
    final PDColorSpace colorSpace = pdImage.getColorSpace();
    final int numComponents = colorSpace.getNumberOfComponents();
    final int width = pdImage.getWidth();
    final int height = pdImage.getHeight();
    final int bitsPerComponent = pdImage.getBitsPerComponent();
    final float[] decode = getDecodeArray(pdImage);

    // read bit stream
    ImageInputStream iis = null;//  w  w  w .j a  v a 2  s  .c  o  m
    try {
        // create stream
        iis = new MemoryCacheImageInputStream(pdImage.createInputStream());
        final float sampleMax = (float) Math.pow(2, bitsPerComponent) - 1f;
        final boolean isIndexed = colorSpace instanceof PDIndexed;

        // init color key mask
        float[] colorKeyRanges = null;
        BufferedImage colorKeyMask = null;
        if (colorKey != null) {
            colorKeyRanges = colorKey.toFloatArray();
            colorKeyMask = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        }

        // calculate row padding
        int padding = 0;
        if (width * numComponents * bitsPerComponent % 8 > 0) {
            padding = 8 - (width * numComponents * bitsPerComponent % 8);
        }

        // read stream
        byte[] srcColorValues = new byte[numComponents];
        byte[] alpha = new byte[1];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                boolean isMasked = true;
                for (int c = 0; c < numComponents; c++) {
                    int value = (int) iis.readBits(bitsPerComponent);

                    // color key mask requires values before they are decoded
                    if (colorKeyRanges != null) {
                        isMasked &= value >= colorKeyRanges[c * 2] && value <= colorKeyRanges[c * 2 + 1];
                    }

                    // decode array
                    final float dMin = decode[c * 2];
                    final float dMax = decode[(c * 2) + 1];

                    // interpolate to domain
                    float output = dMin + (value * ((dMax - dMin) / sampleMax));

                    if (isIndexed) {
                        // indexed color spaces get the raw value, because the TYPE_BYTE
                        // below cannot be reversed by the color space without it having
                        // knowledge of the number of bits per component
                        srcColorValues[c] = (byte) Math.round(output);
                    } else {
                        // interpolate to TYPE_BYTE
                        int outputByte = Math
                                .round(((output - Math.min(dMin, dMax)) / Math.abs(dMax - dMin)) * 255f);

                        srcColorValues[c] = (byte) outputByte;
                    }
                }
                raster.setDataElements(x, y, srcColorValues);

                // set alpha channel in color key mask, if any
                if (colorKeyMask != null) {
                    alpha[0] = (byte) (isMasked ? 255 : 0);
                    colorKeyMask.getRaster().setDataElements(x, y, alpha);
                }
            }

            // rows are padded to the nearest byte
            iis.readBits(padding);
        }

        // use the color space to convert the image to RGB
        BufferedImage rgbImage = colorSpace.toRGBImage(raster);

        // apply color mask, if any
        if (colorKeyMask != null) {
            return applyColorKeyMask(rgbImage, colorKeyMask);
        } else {
            return rgbImage;
        }
    } finally {
        if (iis != null) {
            iis.close();
        }
    }
}

From source file:com.AandR.beans.plotting.imagePlotPanel.CanvasPanel.java

/**
 *
 * @param dataLocal// www .  ja  v  a 2s.c  o m
 * @param isAutoScaled
 * @return
 */
public BufferedImage convertDataToImage(double[][] data, double dataMin, double dataMax) {
    BufferedImage image = new BufferedImage(data.length, data[0].length, BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();

    double thisValue;
    int[] thisRowOfPixels = new int[3 * data.length];
    int[] thisPixelValue = new int[3];
    int i, j;
    double scale = 255.0 / (dataMax - dataMin);
    for (j = 0; j < data[0].length; j++) {
        for (i = 0; i < data.length; i++) {
            thisValue = scale * (data[i][j] - dataMin);
            //if(thisValue<0.0)
            //  thisValue = 0.0;
            //else if(thisValue>255.0)
            //  thisValue = 255.0;

            thisPixelValue = colorMap.getColorValue((int) thisValue);
            thisRowOfPixels[3 * i + 0] = thisPixelValue[0];
            thisRowOfPixels[3 * i + 1] = thisPixelValue[1];
            thisRowOfPixels[3 * i + 2] = thisPixelValue[2];
        }
        raster.setPixels(0, j, data.length, 1, thisRowOfPixels);
    }
    return image;
}