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:org.geoserver.jai.ConcurrentTileFactory.java

/**
 * Builds a new tile, eventually recycling the data array backing it
 *//* w  ww .  ja v a2  s  .  c o m*/
public WritableRaster createTile(SampleModel sampleModel, Point location) {
    // sanity checks
    if (sampleModel == null) {
        throw new NullPointerException("sampleModel cannot be null");
    }
    if (location == null) {
        location = new Point(0, 0);
    }

    DataBuffer db = null;

    // get the three elements making the key into the recycled array map
    int type = sampleModel.getTransferType();
    long numBanks = 0;
    long size = 0;
    if (sampleModel instanceof ComponentSampleModel) {
        ComponentSampleModel csm = (ComponentSampleModel) sampleModel;
        numBanks = getNumBanksCSM(csm);
        size = getBufferSizeCSM(csm);
    } else if (sampleModel instanceof MultiPixelPackedSampleModel) {
        MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sampleModel;
        numBanks = 1;
        int dataTypeSize = DataBuffer.getDataTypeSize(type);
        size = mppsm.getScanlineStride() * mppsm.getHeight()
                + (mppsm.getDataBitOffset() + dataTypeSize - 1) / dataTypeSize;
    } else if (sampleModel instanceof SinglePixelPackedSampleModel) {
        SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel;
        numBanks = 1;
        size = sppsm.getScanlineStride() * (sppsm.getHeight() - 1) + sppsm.getWidth();
    }

    if (size > 0) {
        // try to build a new data buffer starting from 
        Object array = recycledArrays.getRecycledArray(type, numBanks, size);
        if (array != null) {
            switch (type) {
            case DataBuffer.TYPE_BYTE: {
                byte[][] bankData = (byte[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (byte) 0);
                }
                db = new DataBufferByte(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_USHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferUShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_SHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_INT: {
                int[][] bankData = (int[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0);
                }
                db = new DataBufferInt(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_FLOAT: {
                float[][] bankData = (float[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0F);
                }
                db = DataBufferUtils.createDataBufferFloat(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_DOUBLE: {
                double[][] bankData = (double[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0);
                }
                db = DataBufferUtils.createDataBufferDouble(bankData, (int) size);
            }
                break;
            default:
                throw new IllegalArgumentException("Unknown array type");
            }
        }
    }

    if (db == null) {
        db = sampleModel.createDataBuffer();
    }

    return Raster.createWritableRaster(sampleModel, db, location);
}

From source file:com.bc.ceres.jai.opimage.ReinterpretOpImage.java

private void reformat(Raster sourceRaster, WritableRaster targetRaster, Rectangle targetRectangle) {
    final int sourceDataType = sourceRaster.getSampleModel().getDataType();
    final int targetDataType = targetRaster.getSampleModel().getDataType();
    final PixelAccessor sourceAcc = new PixelAccessor(getSourceImage(0));
    final PixelAccessor targetAcc = new PixelAccessor(this);
    final UnpackedImageData sourcePixels;
    final UnpackedImageData targetPixels;

    sourcePixels = sourceAcc.getPixels(sourceRaster, targetRectangle, sourceDataType, false);

    switch (sourceDataType) {
    case DataBuffer.TYPE_BYTE:
        if (interpretationType == ReinterpretDescriptor.INTERPRET_BYTE_SIGNED) {
            targetPixels = targetAcc.getPixels(targetRaster, targetRectangle, targetDataType, true);
            reformatSByte(sourcePixels, targetPixels, targetRectangle);
            break;
        }//from ww  w  . j  a v a2s  .c  o  m
    case DataBuffer.TYPE_INT:
        if (interpretationType == ReinterpretDescriptor.INTERPRET_INT_UNSIGNED) {
            targetPixels = targetAcc.getPixels(targetRaster, targetRectangle, targetDataType, true);
            reformatUInt(sourcePixels, targetPixels, targetRectangle);
            break;
        }
    default:
        targetPixels = sourcePixels;
    }

    targetAcc.setPixels(targetPixels);
}

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

public byte[] getEmptyTile(int width, int height, String format) throws Exception {
    //return an empty image

    ImageResponseWriter writer = getImageResponseWriter(format);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int bands;//from  w  ww .j  a v a  2s  . c o  m
    Double[] nodatas;
    if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        bands = 3;
        nodatas = new Double[] { 0.0, 0.0, 0.0 };
    } else {
        bands = 4;
        nodatas = new Double[] { 0.0, 0.0, 0.0, 0.0 };
    }

    Raster raster = RasterUtils.createEmptyRaster(width, height, bands, DataBuffer.TYPE_BYTE, nodatas);
    writer.writeToStream(raster, ArrayUtils.toPrimitive(nodatas), baos);
    byte[] imageData = baos.toByteArray();
    IOUtils.closeQuietly(baos);
    return imageData;

}

From source file:GraphicsUtil.java

/**
 * Creates a new raster that has a <b>copy</b> of the data in
 * <tt>ras</tt>.  This is highly optimized for speed.  There is
 * no provision for changing any aspect of the SampleModel.
 * However you can specify a new location for the returned raster.
 *
 * This method should be used when you need to change the contents
 * of a Raster that you do not "own" (ie the result of a
 * <tt>getData</tt> call)./*from   www  .j  a  v  a 2  s  .  c  o  m*/
 *
 * @param ras The Raster to copy.
 *
 * @param minX The x location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @param minY The y location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @return    A writable copy of <tt>ras</tt>
 */
public static WritableRaster copyRaster(Raster ras, int minX, int minY) {
    WritableRaster ret = Raster.createWritableRaster(ras.getSampleModel(), new Point(0, 0));
    ret = ret.createWritableChild(ras.getMinX() - ras.getSampleModelTranslateX(),
            ras.getMinY() - ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null);

    // Use System.arraycopy to copy the data between the two...
    DataBuffer srcDB = ras.getDataBuffer();
    DataBuffer retDB = ret.getDataBuffer();
    if (srcDB.getDataType() != retDB.getDataType()) {
        throw new IllegalArgumentException("New DataBuffer doesn't match original");
    }
    int len = srcDB.getSize();
    int banks = srcDB.getNumBanks();
    int[] offsets = srcDB.getOffsets();
    for (int b = 0; b < banks; b++) {
        switch (srcDB.getDataType()) {
        case DataBuffer.TYPE_BYTE: {
            DataBufferByte srcDBT = (DataBufferByte) srcDB;
            DataBufferByte retDBT = (DataBufferByte) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_INT: {
            DataBufferInt srcDBT = (DataBufferInt) srcDB;
            DataBufferInt retDBT = (DataBufferInt) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_SHORT: {
            DataBufferShort srcDBT = (DataBufferShort) srcDB;
            DataBufferShort retDBT = (DataBufferShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        case DataBuffer.TYPE_USHORT: {
            DataBufferUShort srcDBT = (DataBufferUShort) srcDB;
            DataBufferUShort retDBT = (DataBufferUShort) retDB;
            System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len);
        }
        }
    }

    return ret;
}

From source file:nitf.imageio.NITFReader.java

@Override
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException {
    checkIndex(imageIndex);/*from   w  w w .  j  av  a2 s . co m*/

    List<ImageTypeSpecifier> l = new ArrayList<ImageTypeSpecifier>();

    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        String irep = subheader.getImageRepresentation().getStringData().trim();
        String pvType = subheader.getPixelValueType().getStringData().trim();
        int bandCount = subheader.getBandCount();
        int nbpp = subheader.getNumBitsPerPixel().getIntData();

        // if (NITFUtils.isCompressed(record, imageIndex))
        // {
        // throw new NotImplementedException(
        // "Only uncompressed imagery is currently supported");
        // }
        int nBytes = ((nbpp - 1) / 8) + 1;
        if (nBytes == 1 || nBytes == 2 || (nBytes == 4 && pvType.equals("R"))
                || (nBytes == 8 && pvType.equals("R"))) {
            if (nBytes == 1 && bandCount == 3 && irep.equals("RGB")) {
                ColorSpace rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
                int[] bandOffsets = new int[3];
                for (int i = 0; i < bandOffsets.length; ++i)
                    bandOffsets[i] = i;
                l.add(ImageTypeSpecifier.createInterleaved(rgb, bandOffsets, DataBuffer.TYPE_BYTE, false,
                        false));
            }
            l.add(ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE, false));
        } else {
            throw new NotImplementedException(
                    "Support for pixels of size " + nbpp + " bytes has not been implemented yet");
        }
    } catch (NITFException e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
    return l.iterator();
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}/*w w  w. jav  a2 s  .c o  m*/
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

private static List<RectangularRegion> findSubImageInImage(BufferedImage subImage, BufferedImage image,
        int max) {
    Map<Integer, List<Point>> rgb2offsets = new HashMap<Integer, List<Point>>();
    int sw = subImage.getWidth();
    int sh = subImage.getHeight();
    for (int x = 0; x < sw; ++x) {
        for (int y = 0; y < sh; ++y) {
            int argb = subImage.getRGB(x, y);
            int a = argb >>> 24;
            if (a == 255) {
                Integer rgb = argb & 0xFFFFFF;
                List<Point> offsets = rgb2offsets.get(rgb);
                if (offsets == null) {
                    offsets = new ArrayList<Point>();
                    rgb2offsets.put(rgb, offsets);
                }//from   w  w  w. j  a  va 2  s.co  m
                offsets.add(new Point(x, y));
            }
        }
    }
    List<RectangularRegion> result = new ArrayList<RectangularRegion>();
    int w = image.getWidth();
    int h = image.getHeight();
    int[][] p = new int[w][h];
    Raster raster = image.getRaster();
    if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
        byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
        int bytesPerPixel = (bytes.length / (w * h));
        ColorModel colorModel = image.getColorModel();
        byte[] buf = new byte[bytesPerPixel];
        for (int x = 0; x < w; ++x) {
            for (int y = 0; y < h; ++y) {
                System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                p[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
            }
        }
    } else if (raster.getTransferType() == DataBuffer.TYPE_INT) {
        for (int x = 0; x < w; ++x) {
            p[x] = (int[]) raster.getDataElements(x, 0, 1, h, null);
        }
    } else {
        throw new RuntimeException("findSubImageInImage not implemented for image transfer type "
                + raster.getTransferType() + " yet.");
    }
    for (int x = 0; x < w; ++x) {
        for (int y = 0; y < h; ++y) {
            Iterator<Map.Entry<Integer, List<Point>>> i = rgb2offsets.entrySet().iterator();
            compareWithSubImageLoop: while (i.hasNext()) {
                Map.Entry<Integer, List<Point>> mapEntry = i.next();
                int expectedRgb = mapEntry.getKey();
                for (Point offset : mapEntry.getValue()) {
                    int xx = x + offset.x;
                    int yy = y + offset.y;
                    if (xx >= w || yy >= h || expectedRgb != p[xx][yy]) {
                        break compareWithSubImageLoop;
                    }
                }
                if (!i.hasNext()) {
                    result.add(new RectangularRegion(x, y, x + (sw - 1), y + (sh - 1)));
                    if (result.size() == max) {
                        return result;
                    }
                }
            }
        }
    }
    return result;
}

From source file:nitf.imagej.NITF_Reader.java

private static Object getPixelsFromBufferedImage(BufferedImage bufImage) {
    DataBuffer dataBuffer = bufImage.getData().getDataBuffer();
    if (dataBuffer.getDataType() == DataBuffer.TYPE_BYTE)
        return ((DataBufferByte) dataBuffer).getData();
    else if (dataBuffer.getDataType() == DataBuffer.TYPE_USHORT)
        return ((DataBufferUShort) dataBuffer).getData();
    return null;//from  www  .j ava  2 s  .c o  m
}

From source file:org.mrgeo.rasterops.GeoTiffExporter.java

public static void export(final RenderedImage image, final Bounds bounds, final OutputStream os,
        final boolean replaceNan, final String xmp, final Number nodata) throws IOException {
    OpImageRegistrar.registerMrGeoOps();

    final TIFFEncodeParam param = new TIFFEncodeParam();
    // The version of GDAL that Legion is using requires a tile size > 1
    param.setTileSize(image.getTileWidth(), image.getTileHeight());
    param.setWriteTiled(true);//from w  w w  .  ja  v a2 s. c o m

    // if the image only has 1 pixel, the value of this pixel changes after compressing (especially
    // if this pixel is no data value. e.g -9999 changes to -8192 when read the image back).
    // So don't do compress if the image has only 1 pixel.
    if (image.getWidth() > 1 && image.getHeight() > 1) {
        // Deflate lossless compression (also known as "Zip-in-TIFF")
        param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
        param.setDeflateLevel(Deflater.BEST_COMPRESSION);
    }

    final GeoTIFFDirectory dir = new GeoTIFFDirectory();

    // GTModelTypeGeoKey : using geographic coordinate system.
    dir.addGeoKey(new XTIFFField(1024, XTIFFField.TIFF_SHORT, 1, new char[] { 2 }));
    // GTRasterTypeGeoKey : pixel is point
    dir.addGeoKey(new XTIFFField(1025, XTIFFField.TIFF_SHORT, 1, new char[] { 1 }));
    // GeographicTypeGeoKey : 4326 WGS84
    dir.addGeoKey(new XTIFFField(2048, XTIFFField.TIFF_SHORT, 1, new char[] { 4326 }));
    dir.addGeoKey(new XTIFFField(2049, XTIFFField.TIFF_ASCII, 7, new String[] { "WGS 84" }));
    // GeogAngularUnitsGeoKey : Angular Degree
    dir.addGeoKey(new XTIFFField(2054, XTIFFField.TIFF_SHORT, 1, new char[] { 9102 }));
    if (xmp != null) {
        final byte[] b = xmp.getBytes("UTF8");
        dir.addField(new XTIFFField(700, XTIFFField.TIFF_BYTE, b.length, b));
    }
    dir.getFields();

    final double[] tiePoints = new double[6];
    tiePoints[0] = 0.0;
    tiePoints[1] = 0.0;
    tiePoints[2] = 0.0;
    tiePoints[3] = bounds.getMinX();
    tiePoints[4] = bounds.getMaxY();
    tiePoints[5] = 0.0;
    dir.setTiepoints(tiePoints);
    final double[] pixelScale = new double[3];
    pixelScale[0] = bounds.getWidth() / image.getWidth();
    pixelScale[1] = bounds.getHeight() / image.getHeight();
    pixelScale[2] = 0;
    dir.setPixelScale(pixelScale);

    final Vector<TIFFField> fields = toTiffField(dir.getFields());

    RenderedImage output = image;

    final String[] nullValues = new String[1];
    switch (image.getSampleModel().getDataType()) {
    case DataBuffer.TYPE_DOUBLE:
        nullValues[0] = Double.toString(nodata.doubleValue());
        if (replaceNan) {
            output = ReplaceNanDescriptor.create(image, nodata.doubleValue());
        }
        // Tiff exporter doesn't handle doubles. Yuck!
        output = ConvertToFloatDescriptor.create(output);

        // Double.NaN (our default nodata on ingest) should not be written out as nodata on export
        // (i.e. GeoTiffs imported without NODATA metadata field should be exported as such)
        if (!Double.isNaN(nodata.doubleValue())) {
            fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        }
        break;
    case DataBuffer.TYPE_FLOAT:
        nullValues[0] = Double.toString(nodata.floatValue());
        if (replaceNan) {
            output = ReplaceNanDescriptor.create(image, nodata.floatValue());
        }
        // Float.NaN (our default nodata on ingest) should not be written out as nodata on export
        // (i.e. GeoTiffs imported without NODATA metadata field should be exported as such)
        if (!Float.isNaN(nodata.floatValue())) {
            fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        }
        break;
    case DataBuffer.TYPE_INT:
    case DataBuffer.TYPE_USHORT:
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_BYTE:
        nullValues[0] = Integer.toString(nodata.intValue());
        fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        break;
    }

    param.setExtraFields(fields.toArray(new TIFFField[0]));

    EncodeDescriptor.create(output, os, "TIFF", param, null);
}

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

/**
 * Returns a generic banded WritableRaster
 * /*  w w  w.  j  a v a2  s. co m*/
 * @param numElems
 * @param numLines
 * @param bandOffsets
 * @param dataType
 * @return
 */
public static WritableRaster makeGenericBandedWritableRaster(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_FLOAT)
        d = new DataBufferFloat(numElems * numLines * numBands);
    else
        throw new IllegalArgumentException("Invalid datatype: " + dataType);

    BandedSampleModel bsm = new BandedSampleModel(dataType, numElems, numLines, bandOffsets.length, bandOffsets,
            bandOffsets);

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