Example usage for java.awt.image DataBuffer TYPE_BYTE

List of usage examples for java.awt.image DataBuffer TYPE_BYTE

Introduction

In this page you can find the example usage for java.awt.image DataBuffer TYPE_BYTE.

Prototype

int TYPE_BYTE

To view the source code for java.awt.image DataBuffer TYPE_BYTE.

Click Source Link

Document

Tag for unsigned byte data.

Usage

From source file:nitf.imageio.NITFReader.java

@Override
public Raster readRaster(int imageIndex, ImageReadParam param) throws IOException {
    checkIndex(imageIndex);//from   w  w  w .  j  a  va2s .  c o m

    Rectangle sourceRegion = new Rectangle();
    Rectangle destRegion = new Rectangle();
    computeRegions(param, getWidth(imageIndex), getHeight(imageIndex), null, sourceRegion, destRegion);

    // Set everything to default values
    int sourceXSubsampling = param != null ? param.getSourceXSubsampling() : 1;
    int sourceYSubsampling = param != null ? param.getSourceYSubsampling() : 1;
    Point destinationOffset = param != null ? param.getDestinationOffset() : new Point(0, 0);

    ImageSubheader subheader;
    try {
        subheader = record.getImages()[imageIndex].getSubheader();
    } catch (NITFException e) {
        throw new IOException(ExceptionUtils.getStackTrace(e));
    }
    String irep = subheader.getImageRepresentation().getStringData().trim();
    String pvType = subheader.getPixelValueType().getStringData().trim();
    int nbpp = subheader.getNumBitsPerPixel().getIntData();
    int bandCount = subheader.getBandCount();

    // make the band offsets array, for the output
    int[] bandOffsets = null;
    int[] sourceBands = param != null ? param.getSourceBands() : null;
    if (param != null && param.getDestinationBands() != null)
        bandOffsets = param.getDestinationBands();
    else if (param != null && sourceBands != null) {
        bandOffsets = new int[sourceBands.length];
        for (int i = 0; i < bandOffsets.length; i++)
            bandOffsets[i] = sourceBands[i];
    } else {
        // Setup band offsets -- TODO should we really read ALL bands by
        // default?
        bandOffsets = new int[bandCount];
        for (int i = 0; i < bandOffsets.length; i++)
            bandOffsets[i] = i;
    }

    int nBytes = ((nbpp - 1) / 8) + 1;

    int bufType = -1;

    // byte
    if (nBytes == 1) {
        bufType = DataBuffer.TYPE_BYTE;
    }
    // short
    else if (nBytes == 2) {
        bufType = DataBuffer.TYPE_USHORT;
    }
    // float
    else if (nBytes == 4 && pvType.equals("R")) {
        bufType = DataBuffer.TYPE_FLOAT;
    }
    // double
    else if (nBytes == 8 && pvType.equals("R")) {
        bufType = DataBuffer.TYPE_DOUBLE;
    } else {
        throw new NotImplementedException("not yet implemented");
    }

    WritableRaster ras = ImageIOUtils.makeGenericPixelInterleavedWritableRaster(destRegion.width,
            destRegion.height, bandOffsets.length, bufType);
    checkReadParamBandSettings(param, bandCount, ras.getSampleModel().getNumBands());
    readRaster(imageIndex, sourceRegion, destRegion, sourceXSubsampling, sourceYSubsampling, bandOffsets,
            nBytes, destinationOffset, ras);
    return ras;
}

From source file:ImageComponentByReferenceTest.java

TiledImage() {
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] nBits = { 8, 8, 8, 8 };
    int i, j, k, cc = 255;
    int[] bandOffset = new int[4];
    colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.OPAQUE, 0);
    // Create 9 tiles
    bandOffset[0] = 3;//from   w  w  w.  ja  v a  2  s  . c om
    bandOffset[1] = 2;
    bandOffset[2] = 1;
    bandOffset[3] = 0;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            tile[i][j] = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, 8, 8, 32, 4, bandOffset, null);
        }
    }

    // tile {-2, -1}
    byte[] byteData = ((DataBufferByte) tile[0][0].getDataBuffer()).getData();
    for (i = 4, k = 8 * 4 * 4 + 4 * 4; i < 8; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) cc;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }

    // tile {-1, -1}
    byteData = ((DataBufferByte) tile[1][0].getDataBuffer()).getData();
    for (i = 4, k = 8 * 4 * 4; i < 8; i++) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) cc;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }

    // tile {1, -1}
    byteData = ((DataBufferByte) tile[2][0].getDataBuffer()).getData();
    for (i = 4, k = 8 * 4 * 4; i < 8; i++, k += 16) {
        for (j = 0; j < 4; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }

    // tile {-2, 0}
    byteData = ((DataBufferByte) tile[0][1].getDataBuffer()).getData();
    for (i = 0, k = 16; i < 4; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) cc;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }
    for (i = 4, k = 8 * 4 * 4 + 16; i < 8; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) 0;
        }
    }
    // tile {-1, 0}
    byteData = ((DataBufferByte) tile[1][1].getDataBuffer()).getData();
    for (i = 0, k = 0; i < 4; i++) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) cc;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }
    for (i = 0, k = 8 * 4 * 4; i < 4; i++) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) 0;
        }

        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) cc;
        }

    }

    // tile {0, 0}
    byteData = ((DataBufferByte) tile[2][1].getDataBuffer()).getData();
    for (i = 0, k = 0; i < 4; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }
    for (i = 4, k = 8 * 4 * 4; i < 8; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) cc;
        }
    }

    // tile {-2, 1}
    byteData = ((DataBufferByte) tile[0][2].getDataBuffer()).getData();
    for (i = 4, k = 16; i < 8; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) 0;
        }
    }

    // tile {-1, 1}
    byteData = ((DataBufferByte) tile[1][2].getDataBuffer()).getData();
    for (i = 0, k = 0; i < 8; i++) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) 0;
        }
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) cc;
        }
    }

    // tile {0, 1}
    byteData = ((DataBufferByte) tile[2][2].getDataBuffer()).getData();
    for (i = 4, k = 0; i < 8; i++, k += 16) {
        for (j = 4; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) cc;
        }
    }

    bigTile = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, 16, 16, 64, 4, bandOffset, null);
    ;
    byteData = ((DataBufferByte) bigTile.getDataBuffer()).getData();
    for (i = 0, k = 0; i < 8; i++) {
        for (j = 0; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) cc;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
        for (; j < 16; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) 0;
            byteData[k + 3] = (byte) cc;
        }
    }
    for (; i < 16; i++) {
        for (j = 0; j < 8; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) 0;
        }
        for (; j < 16; j++, k += 4) {
            byteData[k] = (byte) 0;
            byteData[k + 1] = (byte) 0;
            byteData[k + 2] = (byte) cc;
            byteData[k + 3] = (byte) cc;
        }
    }
    checkBoard = new BufferedImage(colorModel, bigTile, false, null);
}

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

/**
 * Returns a generic pixel interleaved WritableRaster
 * //from   ww  w  . ja  v  a  2s  .  c  o m
 * @param numElems
 * @param numLines
 * @param bandOffsets
 * @param dataType
 * @return
 */
public static WritableRaster makeGenericPixelInterleavedWritableRaster(int numElems, int numLines, int numBands,
        int dataType) {
    int[] bandOffsets = new int[numBands];
    for (int i = 0; i < numBands; ++i)
        bandOffsets[i] = i;

    DataBuffer d = null;
    if (dataType == DataBuffer.TYPE_BYTE)
        d = new DataBufferByte(numElems * numLines * numBands);
    else if (dataType == DataBuffer.TYPE_SHORT)
        d = new DataBufferShort(numElems * numLines * numBands);
    else if (dataType == DataBuffer.TYPE_USHORT)
        d = new DataBufferUShort(numElems * numLines * numBands);
    else if (dataType == DataBuffer.TYPE_FLOAT)
        d = new DataBufferFloat(numElems * numLines * numBands);
    else if (dataType == DataBuffer.TYPE_DOUBLE)
        d = new DataBufferDouble(numElems * numLines * numBands);
    else
        throw new IllegalArgumentException("Invalid datatype: " + dataType);

    PixelInterleavedSampleModel pism = new PixelInterleavedSampleModel(dataType, numElems, numLines,
            bandOffsets.length, numElems * bandOffsets.length, bandOffsets);

    SunWritableRaster ras = new SunWritableRaster(pism, d, new Point(0, 0));
    return ras;
}

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

private static Raster read(final byte[] rasterBytes, Writable payload) throws IOException {
    WritableRaster raster;//w ww  . j a v  a2 s  .co  m

    final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes);

    @SuppressWarnings("unused")
    final int headersize = rasterBuffer.getInt(); // this isn't really used anymore...
    final int height = rasterBuffer.getInt();
    final int width = rasterBuffer.getInt();
    final int bands = rasterBuffer.getInt();
    final int datatype = rasterBuffer.getInt();
    final SampleModelType sampleModelType = SampleModelType.values()[rasterBuffer.getInt()];

    SampleModel model;
    switch (sampleModelType) {
    case BANDED:
        model = new BandedSampleModel(datatype, width, height, bands);
        break;
    case MULTIPIXELPACKED:
        throw new NotImplementedException("MultiPixelPackedSampleModel not implemented yet");
        // model = new MultiPixelPackedSampleModel(dataType, w, h, numberOfBits)
    case PIXELINTERLEAVED: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new PixelInterleavedSampleModel(datatype, width, height, pixelStride, scanlineStride,
                bandOffsets);
        break;
    }
    case SINGLEPIXELPACKED:
        throw new NotImplementedException("SinglePixelPackedSampleModel not implemented yet");
        // model = new SinglePixelPackedSampleModel(dataType, w, h, bitMasks);
    case COMPONENT: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new ComponentSampleModel(datatype, width, height, pixelStride, scanlineStride, bandOffsets);
        break;
    }
    default:
        throw new RasterWritableException("Unknown RasterSampleModel type");
    }

    // include the header size param in the count
    int startdata = rasterBuffer.position();

    // calculate the data size
    int[] samplesize = model.getSampleSize();
    int samplebytes = 0;
    for (int ss : samplesize) {
        // bits to bytes
        samplebytes += (ss / 8);
    }
    int databytes = model.getHeight() * model.getWidth() * samplebytes;

    // final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes, headerbytes, databytes);
    // the corner of the raster is always 0,0
    raster = Raster.createWritableRaster(model, null);

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        // we can't use the byte buffer explicitly because the header info is
        // still in it...
        final byte[] bytedata = new byte[databytes];
        rasterBuffer.get(bytedata);

        raster.setDataElements(0, 0, width, height, bytedata);
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final FloatBuffer floatbuff = rasterBuffer.asFloatBuffer();
        final float[] floatdata = new float[databytes / RasterUtils.FLOAT_BYTES];

        floatbuff.get(floatdata);

        raster.setDataElements(0, 0, width, height, floatdata);
        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final DoubleBuffer doublebuff = rasterBuffer.asDoubleBuffer();
        final double[] doubledata = new double[databytes / RasterUtils.DOUBLE_BYTES];

        doublebuff.get(doubledata);

        raster.setDataElements(0, 0, width, height, doubledata);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final IntBuffer intbuff = rasterBuffer.asIntBuffer();
        final int[] intdata = new int[databytes / RasterUtils.INT_BYTES];

        intbuff.get(intdata);

        raster.setDataElements(0, 0, width, height, intdata);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final ShortBuffer shortbuff = rasterBuffer.asShortBuffer();
        final short[] shortdata = new short[databytes / RasterUtils.SHORT_BYTES];
        shortbuff.get(shortdata);
        raster.setDataElements(0, 0, width, height, shortdata);
        break;
    }
    default:
        throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
    }

    // should we even try to extract the payload?
    if (payload != null) {
        // test to see if this is a raster with a possible payload
        final int payloadStart = startdata + databytes;
        if (rasterBytes.length > payloadStart) {
            // extract the payload
            final ByteArrayInputStream bais = new ByteArrayInputStream(rasterBytes, payloadStart,
                    rasterBytes.length - payloadStart);
            final DataInputStream dis = new DataInputStream(bais);
            payload.readFields(dis);
        }
    }
    return raster;
}

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

public static int toTileType(final String tiletype) {
    if (tiletype.equals("Byte")) {
        return DataBuffer.TYPE_BYTE;
    }// w  w  w . ja  v  a 2  s.com
    if (tiletype.equals("Float")) {
        return DataBuffer.TYPE_FLOAT;
    }
    if (tiletype.equals("Double")) {
        return DataBuffer.TYPE_DOUBLE;
    }
    if (tiletype.equals("Int")) {
        return DataBuffer.TYPE_INT;
    }
    if (tiletype.equals("Short")) {
        return DataBuffer.TYPE_SHORT;
    }
    if (tiletype.equals("UShort")) {
        return DataBuffer.TYPE_USHORT;
    }

    return DataBuffer.TYPE_UNDEFINED;
}

From source file:TrackerPanel.java

private void drawUserDepths(Graphics2D g2d) {
    // define an 8-bit RGB channel color model
    ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] { 8, 8, 8 }, false, false, ComponentColorModel.OPAQUE, DataBuffer.TYPE_BYTE);

    // fill the raster with the depth image bytes
    DataBufferByte dataBuffer = new DataBufferByte(imgbytes, imWidth * imHeight * 3);

    WritableRaster raster = Raster.createInterleavedRaster(dataBuffer, imWidth, imHeight, imWidth * 3, 3,
            new int[] { 0, 1, 2 }, null);

    // combine color model and raster to create a BufferedImage
    BufferedImage image = new BufferedImage(colorModel, raster, false, null);

    g2d.drawImage(image, 0, 0, null);/*from w  w  w .j  a  va2  s  . co m*/
}

From source file:omr.jai.TestImage3.java

public static void print(PlanarImage pi) {
        // Show the image dimensions and coordinates.
        System.out.print("Image Dimensions: ");
        System.out.print(pi.getWidth() + "x" + pi.getHeight() + " pixels");

        // Remember getMaxX and getMaxY return the coordinate of the next point!
        System.out.println(" (from " + pi.getMinX() + "," + pi.getMinY() + " to " + (pi.getMaxX() - 1) + ","
                + (pi.getMaxY() - 1) + ")");
        if ((pi.getNumXTiles() != 1) || (pi.getNumYTiles() != 1)) { // Is it tiled?
            // Tiles number, dimensions and coordinates.
            System.out.print("Tiles: ");
            System.out.print(pi.getTileWidth() + "x" + pi.getTileHeight() + " pixels" + " (" + pi.getNumXTiles()
                    + "x" + pi.getNumYTiles() + " tiles)");
            System.out.print(" (from " + pi.getMinTileX() + "," + pi.getMinTileY() + " to " + pi.getMaxTileX() + ","
                    + pi.getMaxTileY() + ")");
            System.out.println(" offset: " + pi.getTileGridXOffset() + "," + pi.getTileGridXOffset());
        }/*from w w w  .  ja v  a 2 s.  com*/

        // Display info about the SampleModel of the image.
        SampleModel sm = pi.getSampleModel();
        System.out.println("Number of bands: " + sm.getNumBands());
        System.out.print("Data type: ");
        switch (sm.getDataType()) {
        case DataBuffer.TYPE_BYTE:
            System.out.println("byte");
            break;
        case DataBuffer.TYPE_SHORT:
            System.out.println("short");
            break;
        case DataBuffer.TYPE_USHORT:
            System.out.println("ushort");
            break;
        case DataBuffer.TYPE_INT:
            System.out.println("int");
            break;
        case DataBuffer.TYPE_FLOAT:
            System.out.println("float");
            break;
        case DataBuffer.TYPE_DOUBLE:
            System.out.println("double");
            break;
        case DataBuffer.TYPE_UNDEFINED:
            System.out.println("undefined");
            break;
        }

        // Display info about the ColorModel of the image.
        ColorModel cm = pi.getColorModel();
        if (cm != null) {
            System.out.println("Number of color components: " + cm.getNumComponents());
            System.out.println("Bits per pixel: " + cm.getPixelSize());
            System.out.print("Image Transparency: ");
            switch (cm.getTransparency()) {
            case Transparency.OPAQUE:
                System.out.println("opaque");
                break;
            case Transparency.BITMASK:
                System.out.println("bitmask");
                break;
            case Transparency.TRANSLUCENT:
                System.out.println("translucent");
                break;
            }
        } else
            System.out.println("No color model.");
    }

From source file:org.photovault.imginfo.CreateCopyImageCommand.java

/**
 Helper function to save a rendered image to file
 @param instanceFile The file into which the image will be saved
 @param img Image that willb e saved/*from ww w  .j ava 2  s . c o  m*/
 @param xmpData XPM metadata packet that should be saved with the image
 @throws PhotovaultException if saving does not succeed
 */
protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException {
    ImageOutputStream out = null;
    log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath());
    try {
        out = new FileImageOutputStream(instanceFile);
    } catch (IOException e) {
        log.error("Error writing image: " + e.getMessage());
        throw new PhotovaultException(e.getMessage());
    }
    if (img.getSampleModel().getSampleSize(0) == 16) {
        log.debug("16 bit image, converting to 8 bits");
        double[] subtract = new double[1];
        subtract[0] = 0;
        double[] divide = new double[1];
        divide[0] = 1. / 256.;
        // Now we can rescale the pixels gray levels:
        ParameterBlock pbRescale = new ParameterBlock();
        pbRescale.add(divide);
        pbRescale.add(subtract);
        pbRescale.addSource(img);
        PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null);
        // Make sure it is a byte image - force conversion.
        ParameterBlock pbConvert = new ParameterBlock();
        pbConvert.addSource(outputImage);
        pbConvert.add(DataBuffer.TYPE_BYTE);
        img = JAI.create("format", pbConvert);
    }

    IIOImage iioimg = new IIOImage(img, null, null);

    /*
     Not all encoders support metadata handling
     */
    Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter imgwriter = null;
    while (writers.hasNext()) {
        imgwriter = (ImageWriter) writers.next();
        if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) {
            // Break on finding the core provider.
            break;
        }
    }
    if (imgwriter == null) {
        System.err.println("Cannot find core JPEG writer!");
    }
    imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() {

        public void warningOccurred(ImageWriter arg0, int arg1, String arg2) {
            log.warn("Warning from ImageWriter: " + arg2);
        }
    });
    ImageWriteParam params = imgwriter.getDefaultWriteParam();
    ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img);
    IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null);

    IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
    NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence");
    if (markerSeqNodes.getLength() > 0) {
        IIOMetadataNode xmpNode = new IIOMetadataNode("unknown");
        xmpNode.setAttribute("MarkerTag", "225");
        xmpNode.setUserObject(xmpData);
        markerSeqNodes.item(0).appendChild(xmpNode);
    }

    try {
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop);
    } catch (Exception e) {
        log.warn("error editing metadata: " + e.getMessage());
        e.printStackTrace();
        throw new PhotovaultException("error setting image metadata: \n" + e.getMessage());
    }

    iioimg.setMetadata(metadata);

    try {
        imgwriter.setOutput(out);
        imgwriter.write(iioimg);
    } catch (IOException e) {
        log.warn("Exception while encoding" + e.getMessage());
        throw new PhotovaultException(
                "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            log.warn("Exception while closing file: " + e.getMessage());
            imgwriter.dispose();
            throw new PhotovaultException(
                    "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());

        }
        imgwriter.dispose();
    }
    log.debug("Exit: saveImage");
}

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.
 * //  ww  w . ja v  a  2s.co 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: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// ww  w.  j a v a2s .  c  o m
 * @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();
        }
    }
}