Example usage for java.awt.image Raster getWidth

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

Introduction

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

Prototype

public final int getWidth() 

Source Link

Document

Returns the width in pixels of the Raster.

Usage

From source file:org.geoserver.wms.map.RenderedImageMapOutputFormatTest.java

@Test
public void testGetMapUntiledBigSize() throws Exception {
    final int mapWidth = 8192;
    final int mapHeight = 8192;
    GetMapRequest request = new GetMapRequest();
    CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
    ReferencedEnvelope bbox = new ReferencedEnvelope(new Envelope(145, 146, -43, -41), crs);
    request.setBbox(bbox);// ww w. jav  a 2 s .  c om
    request.setHeight(mapHeight);
    request.setWidth(mapWidth);
    request.setSRS("urn:x-ogc:def:crs:EPSG:4326");
    request.setFormat("image/png");
    request.setTransparent(true);

    final WMSMapContent map = new WMSMapContent(request);
    map.setMapHeight(mapHeight);
    map.setMapWidth(mapWidth);
    map.setBgColor(BG_COLOR);
    map.setTransparent(true);
    map.getViewport().setBounds(bbox);
    addRasterToMap(map, TAZ_BYTE);
    map.getViewport().setBounds(bbox);

    RenderedImageMap imageMap = this.rasterMapProducer.produceMap(map);
    RenderedOp op = (RenderedOp) imageMap.getImage();
    Point[] tileIndices = op.getTileIndices(new Rectangle(0, 0, mapWidth, mapHeight));

    // Assert we are getting more than a single huge tile.
    assertTrue(tileIndices.length > 1);

    Raster tile = op.getTile(0, 0);
    assertNotNull(tile);

    // check that inner tiling has not be set to mapWidth * mapHeight
    assertTrue(tile.getWidth() < mapWidth);
    assertTrue(tile.getHeight() < mapHeight);

    ImageUtilities.disposePlanarImageChain(op);
    imageMap.dispose();

}

From source file:org.geoserver.wps.gs.raster.algebra.JiffleScriptProcessTest.java

/**
 * Private method for ensuring the validity of the output image.
 * //from  ww w  .  j  a v a  2  s .  c  o m
 * @param outputImage RenderedImage extracted from the output coverage
 * @param inputCoverages Input Coverages used.
 * @param values
 */
private void checkExecution(RenderedImage outputImage, int[] values, GridCoverage2D... inputCoverages) {

    RenderedImage inputImage = inputCoverages[0].getRenderedImage();

    int numBands = outputImage.getSampleModel().getNumBands();

    int minTileX = outputImage.getMinTileX();
    int minTileY = outputImage.getMinTileY();
    int maxTileX = outputImage.getNumXTiles() + minTileX;
    int maxTileY = outputImage.getNumYTiles() + minTileY;

    int minX;
    int minY;
    int maxX;
    int maxY;

    Raster inputTile;
    Raster outputTile;

    int inputValue;
    int outputValue;
    // Cycle on each tile
    int valueOver0;

    for (int b = 0; b < numBands; b++) {

        valueOver0 = values[b];

        for (int xTile = minTileX; xTile < maxTileX; xTile++) {
            for (int yTile = minTileY; yTile < maxTileY; yTile++) {

                inputTile = inputImage.getTile(xTile, yTile);
                outputTile = outputImage.getTile(xTile, yTile);

                minX = inputTile.getMinX();
                minY = inputTile.getMinY();

                maxX = inputTile.getWidth() + minX;
                maxY = inputTile.getHeight() + minY;
                // Cycle on the x axis
                for (int x = minX; x < maxX; x++) {
                    // Cycle on the y axis
                    for (int y = minY; y < maxY; y++) {
                        inputValue = inputTile.getSample(x, y, b);
                        outputValue = outputTile.getSample(x, y, b);
                        // Check if the script operation is performed correctly
                        if (inputValue > 0) {
                            assertEquals(outputValue, valueOver0);
                        } else {
                            assertEquals(outputValue, LESS_THAN_ZERO_BAND_0);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.geotools.gce.imagemosaic.ImageMosaicReaderTest.java

@Test
//    @Ignore//from  w  w  w.  j  a  v  a  2  s.  co m
public void testRequestInOut() throws Exception {
    final AbstractGridFormat format = TestUtils.getFormat(rgbAURL);
    final ImageMosaicReader reader = TestUtils.getReader(rgbAURL, format);

    assertNotNull(reader);

    // ask to extract an area that is inside the coverage bbox, so that the area is partly
    // inside the raster, and partly outside
    final ParameterValue<GridGeometry2D> ggp = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue();
    Envelope2D env = new Envelope2D(reader.getCrs(), 64887, 2499342, 646897 - 64887, 3155705 - 2499342);
    GridGeometry2D gg = new GridGeometry2D(new GridEnvelope2D(0, 0, 100, 100), (Envelope) env);
    ggp.setValue(gg);

    // red background
    final ParameterValue<double[]> bgp = ImageMosaicFormat.BACKGROUND_VALUES.createValue();
    bgp.setValue(new double[] { 255, 0, 0, 255 });

    // read and check we actually got a coverage in the requested area
    GridCoverage2D coverage = reader.read(new GeneralParameterValue[] { ggp, bgp });
    assertNotNull(coverage);
    System.out.println(coverage.getEnvelope2D());
    System.out.println(env);
    assertTrue(coverage.getEnvelope2D().contains((Rectangle2D) env));

    // and that the color is the expected one given the background values provided
    RenderedImage ri = coverage.getRenderedImage();
    // ImageIO.write(ri, "PNG", new File("/tmp/mix.png"));
    System.out.println(ri.getNumXTiles());
    System.out.println(ri.getNumYTiles());
    int[] pixel = new int[4];
    Raster tile = ri.getTile(ri.getMinTileX() + ri.getNumXTiles() - 1,
            ri.getMinTileY() + ri.getNumYTiles() - 1);
    tile.getPixel(tile.getWidth() / 2, tile.getHeight() / 2, pixel);
    assertEquals(255, pixel[0]);
    assertEquals(0, pixel[1]);
    assertEquals(0, pixel[2]);
    assertEquals(255, pixel[3]);
}

From source file:org.gmdev.pdftrick.utils.CustomExtraImgReader.java

/**
 * Convert image from Cmyk to Rgb profile
 * @param cmykRaster//from w  w  w. j  a v a2 s.co m
 * @param cmykProfile
 * @return The BufferedImage obj
 * @throws IOException
 */
private static BufferedImage convertCmykToRgb(Raster cmykRaster, ICC_Profile cmykProfile) throws IOException {
    if (cmykProfile == null) {
        cmykProfile = ICC_Profile.getInstance(
                CustomExtraImgReader.class.getResourceAsStream(Consts.RESOURCEPATH + Consts.GENERICICCFILE));
    }
    if (cmykProfile.getProfileClass() != ICC_Profile.CLASS_DISPLAY) {
        byte[] profileData = cmykProfile.getData();
        if (profileData[ICC_Profile.icHdrRenderingIntent] == ICC_Profile.icPerceptual) {
            intToBigEndian(ICC_Profile.icSigDisplayClass, profileData, ICC_Profile.icHdrDeviceClass);
            cmykProfile = ICC_Profile.getInstance(profileData);
        }
    }

    ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile);
    BufferedImage rgbImage = new BufferedImage(cmykRaster.getWidth(), cmykRaster.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();
    ColorSpace rgbCS = rgbImage.getColorModel().getColorSpace();
    ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null);
    cmykToRgb.filter(cmykRaster, rgbRaster);
    return rgbImage;
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

/**
 * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are
 * converted, other images are left untouched.
 *
 * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either,
 * so we have to convert raster data to a JPG with RGB color space.
 *
 * The technique used in this method is due to Mark Stephens, and free for any use. See
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or
 * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html
 *
 * @param is the image data/* w  w w. j  a  va2s.c  om*/
 * @param colorModel the color model of the image
 * @return the RGB version of the supplied image
 */
public static InputStream convertToRGB(InputStream is, ColorModel colorModel)
        throws IOException, UnsupportedImageException {
    if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) {
        return is;
    }

    // Get an ImageReader.
    ImageInputStream input = ImageIO.createImageInputStream(is);

    try {
        Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
        if (readers == null || !readers.hasNext()) {
            throw new UnsupportedImageException("No ImageReaders found");
        }

        ImageReader reader = readers.next();
        reader.setInput(input);
        Raster raster = reader.readRaster(0, reader.getDefaultReadParam());

        int w = raster.getWidth();
        int h = raster.getHeight();
        byte[] rgb = new byte[w * h * 3];

        switch (colorModel) {
        case YCCK: {
            float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
            float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
            float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
            float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);

            for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];

                double val = y + 1.402 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y + 1.772 * (cb - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
            }
            break;
        }
        case CMYK: {
            int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
            int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
            int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
            int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);

            for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
                int c = 255 - C[i];
                int m = 255 - M[i];
                int y = 255 - Y[i];
                int k = 255 - K[i];
                float kk = k / 255f;

                rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
                rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
                rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
            }
            break;
        }
        }

        // from other image types we know InterleavedRaster's can be
        // manipulated by AffineTransformOp, so create one of those.
        raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3,
                new int[] { 0, 1, 2 }, null);

        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);
        BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", os);

        return new ByteArrayInputStream(os.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
        if (input != null) {
            input.close();
        }
    }
}

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

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

    byte[] pixels;

    final Object elements = raster.getDataElements(raster.getMinX(), raster.getMinY(), raster.getWidth(),
            raster.getHeight(), null);//from   www .  j  av a2  s .c  o  m

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

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

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

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

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

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

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

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

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

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

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

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

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

    return pixels;
}

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://w ww .  ja  v a  2s  .  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.
 * /*ww w.ja v  a 2s  . co m*/
 * @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

public void calculateStats(final Raster r) {
    count = 0;/*from   w ww.j  av a  2s.  co  m*/
    sum = 0;
    for (int py = r.getMinY(); py < r.getMinY() + r.getHeight(); py++) {
        for (int px = r.getMinX(); px < r.getMinX() + r.getWidth(); px++) {
            final double v = r.getSampleDouble(px, py, 0);
            min = Math.min(min, v);
            max = Math.max(max, v);
            if (!Double.isNaN(v)) {
                sum += v;
                count++;
            }
        }
    }
    mean = sum / count;
}

From source file:org.mrgeo.services.mrspyramid.MrsPyramidServiceTest.java

@Test
@Category(UnitTest.class)
public void testCreateColorSwatch() throws Exception {
    String input = TestUtils.composeInputDir(ColorScaleResourceTest.class);
    MrsPyramidService testInstance = new MrsPyramidService(new Properties());
    int width = 100;
    int height = 10;

    Raster ri = testInstance.createColorScaleSwatch(createRainbowColorScale(), "png", width, height);
    assertEquals(ri.getWidth(), width);
    assertEquals(ri.getHeight(), height);
    TestUtils.compareRasters(new File(input + "colorswatch.png"), ri);

    width = 20;//from w  ww . j  a va  2 s  . co m
    height = 200;

    ri = testInstance.createColorScaleSwatch(createRainbowColorScale(), "png", width, height);
    assertEquals(ri.getWidth(), width);
    assertEquals(ri.getHeight(), height);
    TestUtils.compareRasters(new File(input + "colorswatchvertical.png"), ri);
}