Example usage for java.awt.image Raster getNumBands

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

Introduction

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

Prototype

public final int getNumBands() 

Source Link

Document

Returns the number of bands (samples per pixel) in this Raster.

Usage

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
public static MessageDigest md5(final @Nonnull Raster raster) throws NoSuchAlgorithmException {
    final MessageDigest md5 = MessageDigest.getInstance("MD5");

    for (int b = 0; b < raster.getNumBands(); b++) {
        for (int y = 0; y < raster.getHeight(); y++) {
            for (int x = 0; x < raster.getWidth(); x++) {
                final int sample = raster.getSample(x, y, b) & 0xffff;
                md5.update((byte) ((sample >>> 24) & 0xff));
                md5.update((byte) ((sample >>> 16) & 0xff));
                md5.update((byte) ((sample >>> 8) & 0xff));
                md5.update((byte) ((sample >>> 0) & 0xff));
            }/*ww w. ja v  a 2  s . c  om*/
        }
    }

    return md5;
}

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
public static void dumpRasterAsText(final @Nonnull Raster raster, final @Nonnull PrintWriter pw) {
    final int width = raster.getWidth();
    final int height = raster.getHeight();
    final int bandCount = raster.getNumBands();
    logger.fine("Dumping raster %d x %d x %d", width, height, bandCount);

    for (int y = 0; y < height; y++) {
        for (int b = 0; b < bandCount; b++) {
            pw.printf("y=%04d b=%1d : ", y, b);

            for (int x = 0; x < width; x++) {
                final int sample = raster.getSample(x, y, b) & 0xffff;
                pw.printf("%04x ", sample);
            }/* w  ww . ja v  a 2 s  .c o m*/

            pw.println();
        }
    }
}

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

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

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

From source file:com.alibaba.simpleimage.codec.jpeg.JPEGDecoderFunctionTest.java

protected void compareImage(String name, BufferedImage left, BufferedImage right, boolean ignoreError)
        throws Exception {
    if (left.getWidth() != right.getWidth() || left.getHeight() != right.getHeight()) {
        assertTrue("size not equal", false);
    }//from w ww. ja v a2 s  .c  o  m

    Raster leftRaster = left.getData();
    Raster rightRaster = right.getData();
    int[] leftPixes = new int[4];
    int[] rightPixes = new int[4];

    for (int x = 0; x < right.getWidth(); x++) {
        for (int y = 0; y < right.getHeight(); y++) {
            leftPixes = leftRaster.getPixel(x, y, leftPixes);
            rightPixes = rightRaster.getPixel(x, y, rightPixes);

            for (int i = 0; i < leftRaster.getNumBands(); i++) {
                if (Math.abs(leftPixes[i] - rightPixes[i]) > DIFF_VALUE) {
                    if (!ignoreError) {
                        assertTrue(name + "'s pix not equal, sub is " + (leftPixes[i] - rightPixes[i]), false);
                    }
                }

                leftPixes[i] = 0;
                rightPixes[i] = 0;
            }
        }
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

private BufferedImage getFallbackBufferedImage(ImageReader reader, int pageIndex, ImageReadParam param)
        throws IOException {
    //Work-around found at: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
    //There are some additional ideas there if someone wants to go further.

    // Try reading a Raster (no color conversion).
    Raster raster = reader.readRaster(pageIndex, param);

    // Arbitrarily select a BufferedImage type.
    int imageType;
    switch (raster.getNumBands()) {
    case 1://ww w.j  a  v  a2s.c o m
        imageType = BufferedImage.TYPE_BYTE_GRAY;
        break;
    case 3:
        imageType = BufferedImage.TYPE_3BYTE_BGR;
        break;
    case 4:
        imageType = BufferedImage.TYPE_4BYTE_ABGR;
        break;
    default:
        throw new UnsupportedOperationException();
    }

    // Create a BufferedImage.
    BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), imageType);

    // Set the image data.
    bi.getRaster().setRect(raster);
    return bi;
}

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

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

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

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

    return rgbArray;
}

From source file:org.mrgeo.data.raster.RasterWritable.java

private static void writeHeader(final Raster raster, final OutputStream out) throws IOException {
    final DataOutputStream dos = new DataOutputStream(out);

    int headersize = HEADERSIZE;
    // this is in integers!
    // MAKE SURE TO KEEP THIS CORRECT IF YOU ADD PARAMETERS TO THE HEADER!!!

    final SampleModel model = raster.getSampleModel();
    final SampleModelType modeltype = toSampleModelType(model);

    int[] bandOffsets = null;
    switch (modeltype) {
    case BANDED://from w  w w.ja  va  2  s. c  o m
        break;
    case PIXELINTERLEAVED:
    case COMPONENT:
        bandOffsets = ((ComponentSampleModel) model).getBandOffsets();

        // add pixel-stride, scanline-stride, band offset count, & band offsets to
        // the header count
        headersize += 3 + bandOffsets.length;
        break;
    case MULTIPIXELPACKED:
        break;
    case SINGLEPIXELPACKED:
        break;
    default:
    }

    dos.writeInt(headersize);
    dos.writeInt(raster.getHeight());
    dos.writeInt(raster.getWidth());
    dos.writeInt(raster.getNumBands());
    dos.writeInt(raster.getTransferType());

    dos.writeInt(modeltype.ordinal());

    switch (modeltype) {
    case BANDED:
        break;
    case COMPONENT:
    case PIXELINTERLEAVED: {
        final ComponentSampleModel pism = (ComponentSampleModel) model;
        dos.writeInt(pism.getPixelStride());
        dos.writeInt(pism.getScanlineStride());

        dos.writeInt(bandOffsets.length);
        for (final int bandOffset : bandOffsets) {
            dos.writeInt(bandOffset);
        }
    }
        break;
    case MULTIPIXELPACKED:
        break;
    case SINGLEPIXELPACKED:
        break;
    default:
    }

}

From source file:org.mrgeo.image.ImageStats.java

/**
 * Computes pixel value statistics: min, max, sum, count, & mean for a Raster and returns an array
 * of ImageStats objects, one for each band in the image.
 * /*from  ww w  . ja va2 s.  c  om*/
 * @param raster
 *          the raster to compute stats for
 * @param nodata
 *          the value to ignore
 * @return an array of ImageStats objects
 */
static public void computeAndUpdateStats(final ImageStats[] tileStats, final Raster raster,
        final double[] nodata) throws RasterWritableException {
    final int type = raster.getTransferType();
    Number sample;
    for (int y = 0; y < raster.getHeight(); y++) {
        for (int x = 0; x < raster.getWidth(); x++) {
            for (int b = 0; b < raster.getNumBands(); b++) {
                switch (type) {
                case DataBuffer.TYPE_BYTE:
                case DataBuffer.TYPE_INT:
                case DataBuffer.TYPE_SHORT:
                case DataBuffer.TYPE_USHORT:
                    sample = raster.getSample(x, y, b);
                    break;
                case DataBuffer.TYPE_FLOAT:
                    sample = raster.getSampleFloat(x, y, b);
                    break;
                case DataBuffer.TYPE_DOUBLE:
                    sample = raster.getSampleDouble(x, y, b);
                    break;
                default:
                    throw new RasterWritableException(
                            "Error computing tile statistics. Unsupported raster data type");
                }
                updateStats(tileStats[b], sample, nodata[b]);
            }
        }
    }

}

From source file:org.mrgeo.image.ImageStats.java

/**
 * Computes pixel value statistics: min, max, sum, count, & mean for a Raster and returns an array
 * of ImageStats objects, one for each band in the image.
 * //from   ww  w .  ja  va 2 s .c  om
 * @param raster
 *          the raster to compute stats for
 * @param nodata
 *          the value to ignore
 * @return an array of ImageStats objects
 */
static public ImageStats[] computeStats(final Raster raster, final double[] nodata)
        throws RasterWritableException {
    final ImageStats[] tileStats = initializeStatsArray(raster.getNumBands());
    computeAndUpdateStats(tileStats, raster, nodata);
    return tileStats;
}

From source file:org.mrgeo.resources.tms.TileMapServiceResource.java

@SuppressWarnings("static-method")
@GET//from   w w w.  java 2  s.c om
@Produces("image/*")
@Path("{version}/{raster}/{z}/{x}/{y}.{format}")
public Response getTile(@PathParam("version") final String version, @PathParam("raster") String pyramid,
        @PathParam("z") final Integer z, @PathParam("x") final Integer x, @PathParam("y") final Integer y,
        @PathParam("format") final String format, @QueryParam("color-scale-name") final String colorScaleName,
        @QueryParam("color-scale") final String colorScale, @QueryParam("min") final Double min,
        @QueryParam("max") final Double max, @DefaultValue("1") @QueryParam("maskMax") final Double maskMax,
        @QueryParam("mask") final String mask) {

    final ImageRenderer renderer;
    Raster raster;

    try {
        renderer = (ImageRenderer) ImageHandlerFactory.getHandler(format, ImageRenderer.class);

        // TODO: Need to construct provider properties from the WebRequest using
        // a new security layer and pass those properties.
        // Apply mask if requested
        ProviderProperties providerProperties = SecurityUtils.getProviderProperties();
        if (mask != null && !mask.isEmpty()) {
            raster = renderer.renderImage(pyramid, x, y, z, mask, maskMax, providerProperties);
        } else {
            raster = renderer.renderImage(pyramid, x, y, z, providerProperties);
        }
        if (!(renderer instanceof TiffImageRenderer) && raster.getNumBands() != 3
                && raster.getNumBands() != 4) {
            ColorScale cs = null;
            if (colorScaleName != null) {
                cs = ColorScaleManager.fromName(colorScaleName, props);
            } else if (colorScale != null) {
                cs = ColorScaleManager.fromJSON(colorScale);
            }
            //        else
            //        {
            //          cs = ColorScaleManager.fromPyramid(pyramid, driver);
            //        }

            final double[] extrema = renderer.getExtrema();

            // Check for min/max override values from the request
            if (min != null) {
                extrema[0] = min;
            }
            if (max != null) {
                extrema[1] = max;
            }

            raster = ((ColorScaleApplier) ImageHandlerFactory.getHandler(format, ColorScaleApplier.class))
                    .applyColorScale(raster, cs, extrema, renderer.getDefaultValues());
        }

        // Apply mask if requested
        //      if (mask != null && !mask.isEmpty())
        //      {
        //        try
        //        {
        //          final MrsImagePyramidMetadata maskMetadata = service.getMetadata(mask);
        //
        //          final Raster maskRaster = renderer.renderImage(mask, x, y, z, props, driver);
        //          final WritableRaster wr = RasterUtils.makeRasterWritable(raster);
        //
        //          final int band = 0;
        //          final double nodata = maskMetadata.getDefaultValue(band);
        //
        //          for (int w = 0; w < maskRaster.getWidth(); w++)
        //          {
        //            for (int h = 0; h < maskRaster.getHeight(); h++)
        //            {
        //              final double maskPixel = maskRaster.getSampleDouble(w, h, band);
        //              if (maskPixel > maskMax || Double.compare(maskPixel, nodata) == 0)
        //              {
        //                wr.setSample(w, h, band, nodata);
        //              }
        //            }
        //          }
        //        }
        //        catch (final TileNotFoundException ex)
        //        {
        //          raster = RasterUtils.createEmptyRaster(raster.getWidth(), raster.getHeight(), raster
        //            .getNumBands(), raster.getTransferType(), 0);
        //        }
        //      }

        return ((ImageResponseWriter) ImageHandlerFactory.getHandler(format, ImageResponseWriter.class))
                .write(raster, renderer.getDefaultValues()).build();

    } catch (final IllegalArgumentException e) {
        return Response.status(Status.BAD_REQUEST).entity("Unsupported image format - " + format).build();
    } catch (final IOException e) {
        return Response.status(Status.NOT_FOUND).entity("Tile map not found - " + pyramid).build();
    } catch (final MrsImageException e) {
        return Response.status(Status.NOT_FOUND).entity("Tile map not found - " + pyramid + ": " + z).build();
    } catch (final TileNotFoundException e) {
        // return Response.status(Status.NOT_FOUND).entity("Tile not found").build();
        try {
            final MrsPyramidMetadata metadata = service.getMetadata(pyramid);

            return createEmptyTile(
                    ((ImageResponseWriter) ImageHandlerFactory.getHandler(format, ImageResponseWriter.class)),
                    metadata.getTilesize(), metadata.getTilesize());
        } catch (final Exception e1) {
            log.error("Exception occurred creating blank tile " + pyramid + "/" + z + "/" + x + "/" + y + "."
                    + format, e1);
        }
    } catch (final ColorScale.BadJSONException e) {
        return Response.status(Status.NOT_FOUND).entity("Unable to parse color scale JSON").build();

    } catch (final ColorScale.BadSourceException e) {
        return Response.status(Status.NOT_FOUND).entity("Unable to open color scale file").build();
    } catch (final ColorScale.BadXMLException e) {
        return Response.status(Status.NOT_FOUND).entity("Unable to parse color scale XML").build();
    } catch (final ColorScale.ColorScaleException e) {
        return Response.status(Status.NOT_FOUND).entity("Unable to open color scale").build();
    } catch (final Exception e) {
        log.error("Exception occurred getting tile " + pyramid + "/" + z + "/" + x + "/" + y + "." + format, e);
    }

    return Response.status(Status.INTERNAL_SERVER_ERROR).entity(GENERAL_ERROR).build();
}