List of usage examples for java.awt.image Raster createWritableRaster
public static WritableRaster createWritableRaster(SampleModel sm, Point location)
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 ww w . j a va 2 s.c om*/ * * @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); break; } 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); break; } 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); break; } 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); break; } } } return ret; }
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).//w w w. ja v a 2 s . c om * * @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:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java
/** {@inheritDoc} */ public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { RenderedImage imageData = null; IIOException firstException = null; IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA); boolean ignoreMetadata = (iiometa != null); boolean providerIgnoresICC = false; Source src = session.needSource(info.getOriginalURI()); ImageInputStream imgStream = ImageUtil.needImageInputStream(src); try {/* w w w. j a va2 s. c om*/ Iterator iter = ImageIO.getImageReaders(imgStream); while (iter.hasNext()) { ImageReader reader = (ImageReader) iter.next(); try { imgStream.mark(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(imgStream, false, ignoreMetadata); final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI()); try { if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) { imageData = reader.read(pageIndex, param); } else { imageData = reader.read(pageIndex, param); //imageData = reader.readAsRenderedImage(pageIndex, param); //TODO Reenable the above when proper listeners are implemented //to react to late pixel population (so the stream can be closed //properly). } if (iiometa == null) { iiometa = reader.getImageMetadata(pageIndex); } providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider()); break; //Quit early, we have the image } catch (IndexOutOfBoundsException indexe) { throw new ImageException("Page does not exist. Invalid image index: " + pageIndex); } catch (IllegalArgumentException iae) { //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw //IllegalArgumentExceptions when they have trouble parsing the image. throw new ImageException("Error loading image using ImageIO codec", iae); } catch (IIOException iioe) { if (firstException == null) { firstException = iioe; } else { log.debug("non-first error loading image: " + iioe.getMessage()); } } try { //Try fallback for CMYK images BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param); imageData = bi; firstException = null; //Clear exception after successful fallback attempt break; } catch (IIOException iioe) { //ignore } imgStream.reset(); } finally { reader.dispose(); } } } finally { ImageUtil.closeQuietly(src); //TODO Some codecs may do late reading. } if (firstException != null) { throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException); } if (imageData == null) { throw new ImageException("No ImageIO ImageReader found ."); } ColorModel cm = imageData.getColorModel(); Color transparentColor = null; if (cm instanceof IndexColorModel) { //transparent color will be extracted later from the image } else { if (providerIgnoresICC && cm instanceof ComponentColorModel) { // Apply ICC Profile to Image by creating a new image with a new // color model. ICC_Profile iccProf = tryToExctractICCProfile(iiometa); if (iccProf != null) { ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(), cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType()); WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null); imageData.copyData(wr); BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null); imageData = bi; cm = cm2; } } // ImageIOUtil.dumpMetadataToSystemOut(iiometa); // Retrieve the transparent color from the metadata if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) { Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName); Element dim = ImageIOUtil.getChild(metanode, "Transparency"); if (dim != null) { Element child; child = ImageIOUtil.getChild(dim, "TransparentColor"); if (child != null) { String value = child.getAttribute("value"); if (value == null || value.length() == 0) { //ignore } else if (cm.getNumColorComponents() == 1) { int gray = Integer.parseInt(value); transparentColor = new Color(gray, gray, gray); } else { StringTokenizer st = new StringTokenizer(value); transparentColor = new Color(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); } } } } } if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) { return new ImageBuffered(info, (BufferedImage) imageData, transparentColor); } else { return new ImageRendered(info, imageData, transparentColor); } }
From source file:org.geotools.imageio.netcdf.NetCDFImageReader.java
/** * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam) *//* w w w. j av a2s. c om*/ @Override public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { clearAbortRequest(); final Slice2DIndex slice2DIndex = getSlice2DIndex(imageIndex); final String variableName = slice2DIndex.getVariableName(); final VariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName)); /* * Fetches the parameters that are not already processed by utility * methods like 'getDestination' or 'computeRegions' (invoked below). */ final int strideX, strideY; // final int[] srcBands; final int[] dstBands; if (param != null) { strideX = param.getSourceXSubsampling(); strideY = param.getSourceYSubsampling(); // srcBands = param.getSourceBands(); dstBands = param.getDestinationBands(); } else { strideX = 1; strideY = 1; // srcBands = null; dstBands = null; } /* * Gets the destination image of appropriate size. We create it now * since it is a convenient way to get the number of destination bands. */ final int width = wrapper.getWidth(); final int height = wrapper.getHeight(); /* * Computes the source region (in the NetCDF file) and the destination * region (in the buffered image). Copies those informations into UCAR * Range structure. */ final Rectangle srcRegion = new Rectangle(); final Rectangle destRegion = new Rectangle(); computeRegions(param, width, height, null, srcRegion, destRegion); // Flipping is needed only when the input latitude coordinate is ordered // from min to max if (needsFlipping) { flipVertically(param, height, srcRegion); } int destWidth = destRegion.x + destRegion.width; int destHeight = destRegion.y + destRegion.height; /* * build the ranges that need to be read from each * dimension based on the source region */ final List<Range> ranges = new LinkedList<Range>(); try { // add the ranges the COARDS way: T, Z, Y, X // T int first = slice2DIndex.getTIndex(); int length = 1; int stride = 1; if (first != -1) { ranges.add(new Range(first, first + length - 1, stride)); } // Z first = slice2DIndex.getZIndex(); if (first != -1) { ranges.add(new Range(first, first + length - 1, stride)); } // Y first = srcRegion.y; length = srcRegion.height; stride = strideY; ranges.add(new Range(first, first + length - 1, stride)); // X first = srcRegion.x; length = srcRegion.width; stride = strideX; ranges.add(new Range(first, first + length - 1, stride)); } catch (InvalidRangeException e) { throw netcdfFailure(e); } /* * create the section of multidimensional array indices * that defines the exact data that need to be read * for this image index and parameters */ final Section section = new Section(ranges); /* * Setting SampleModel and ColorModel. */ final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight); final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel); final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0)); final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null); CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis(); boolean flipYAxis = false; try { Array yAxisStart = axis.read(new Section().appendRange(2)); float y1 = yAxisStart.getFloat(0); float y2 = yAxisStart.getFloat(1); if (y2 > y1) { flipYAxis = true; } } catch (InvalidRangeException e) { throw new RuntimeException(e); } /* * Reads the requested sub-region only. */ processImageStarted(imageIndex); final int numDstBands = 1; final float toPercent = 100f / numDstBands; final int type = raster.getSampleModel().getDataType(); final int xmin = destRegion.x; final int ymin = destRegion.y; final int xmax = destRegion.width + xmin; final int ymax = destRegion.height + ymin; for (int zi = 0; zi < numDstBands; zi++) { // final int srcBand = (srcBands == null) ? zi : srcBands[zi]; final int dstBand = (dstBands == null) ? zi : dstBands[zi]; final Array array; try { // TODO leak through array = wrapper.variableDS.read(section); } catch (InvalidRangeException e) { throw netcdfFailure(e); } if (flipYAxis) { final IndexIterator it = array.getIndexIterator(); for (int y = ymax; --y >= ymin;) { for (int x = xmin; x < xmax; x++) { switch (type) { case DataBuffer.TYPE_DOUBLE: { raster.setSample(x, y, dstBand, it.getDoubleNext()); break; } case DataBuffer.TYPE_FLOAT: { raster.setSample(x, y, dstBand, it.getFloatNext()); break; } case DataBuffer.TYPE_BYTE: { byte b = it.getByteNext(); // int myByte = (0x000000FF & ((int) b)); // short anUnsignedByte = (short) myByte; // raster.setSample(x, y, dstBand, anUnsignedByte); raster.setSample(x, y, dstBand, b); break; } default: { raster.setSample(x, y, dstBand, it.getIntNext()); break; } } } } } else { switch (type) { case DataBuffer.TYPE_DOUBLE: { DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer(); double[] samples = new double[destRegion.width * destRegion.height]; doubleBuffer.get(samples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples); break; } case DataBuffer.TYPE_FLOAT: float[] samples = new float[destRegion.width * destRegion.height]; FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer(); floatBuffer.get(samples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples); break; case DataBuffer.TYPE_BYTE: //THIS ONLY WORKS FOR ONE BAND!! raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height, array.getDataAsByteBuffer().array()); break; case DataBuffer.TYPE_INT: IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer(); int[] intSamples = new int[destRegion.width * destRegion.height]; intBuffer.get(intSamples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples); break; default: { final IndexIterator it = array.getIndexIterator(); for (int y = ymin; y < ymax; y++) { for (int x = xmin; x < xmax; x++) { raster.setSample(x, y, dstBand, it.getIntNext()); } } break; } } } /* * Checks for abort requests after reading. It would be a waste of a * potentially good image (maybe the abort request occurred after we * just finished the reading) if we didn't implemented the * 'isCancel()' method. But because of the later, which is checked * by the NetCDF library, we can't assume that the image is * complete. */ if (abortRequested()) { processReadAborted(); return image; } /* * Reports progress here, not in the deeper loop, because the costly * part is the call to 'variable.read(...)' which can't report * progress. The loop that copy pixel values is fast, so reporting * progress there would be pointless. */ processImageProgress(zi * toPercent); } processImageComplete(); return image; }
From source file:org.geotools.imageio.unidata.UnidataImageReader.java
/** * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam) *//*from w ww . j a va 2 s. c om*/ @Override public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { clearAbortRequest(); final UnidataSlice2DIndex slice2DIndex = getSlice2DIndex(imageIndex); final String variableName = slice2DIndex.getVariableName(); final UnidataVariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName)); /* * Fetches the parameters that are not already processed by utility * methods like 'getDestination' or 'computeRegions' (invoked below). */ final int strideX, strideY; // final int[] srcBands; final int[] dstBands; if (param != null) { strideX = param.getSourceXSubsampling(); strideY = param.getSourceYSubsampling(); // srcBands = param.getSourceBands(); dstBands = param.getDestinationBands(); } else { strideX = 1; strideY = 1; // srcBands = null; dstBands = null; } /* * Gets the destination image of appropriate size. We create it now * since it is a convenient way to get the number of destination bands. */ final int width = wrapper.getWidth(); final int height = wrapper.getHeight(); /* * Computes the source region (in the NetCDF file) and the destination * region (in the buffered image). Copies those informations into UCAR * Range structure. */ final Rectangle srcRegion = new Rectangle(); final Rectangle destRegion = new Rectangle(); computeRegions(param, width, height, null, srcRegion, destRegion); flipVertically(param, height, srcRegion); int destWidth = destRegion.x + destRegion.width; int destHeight = destRegion.y + destRegion.height; /* * build the ranges that need to be read from each * dimension based on the source region */ final List<Range> ranges = new LinkedList<Range>(); try { // add the ranges the COARDS way: T, Z, Y, X // T int first = slice2DIndex.getTIndex(); int length = 1; int stride = 1; if (first != -1) { ranges.add(new Range(first, first + length - 1, stride)); } // Z first = slice2DIndex.getZIndex(); if (first != -1) { ranges.add(new Range(first, first + length - 1, stride)); } // Y first = srcRegion.y; length = srcRegion.height; stride = strideY; ranges.add(new Range(first, first + length - 1, stride)); // X first = srcRegion.x; length = srcRegion.width; stride = strideX; ranges.add(new Range(first, first + length - 1, stride)); } catch (InvalidRangeException e) { throw netcdfFailure(e); } /* * create the section of multidimensional array indices * that defines the exact data that need to be read * for this image index and parameters */ final Section section = new Section(ranges); /* * Setting SampleModel and ColorModel. */ final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight); final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel); final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0)); final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null); CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis(); boolean flipYAxis = false; try { Array yAxisStart = axis.read(new Section().appendRange(2)); float y1 = yAxisStart.getFloat(0); float y2 = yAxisStart.getFloat(1); if (y2 > y1) { flipYAxis = true; } } catch (InvalidRangeException e) { throw new RuntimeException(e); } /* * Reads the requested sub-region only. */ processImageStarted(imageIndex); final int numDstBands = 1; final float toPercent = 100f / numDstBands; final int type = raster.getSampleModel().getDataType(); final int xmin = destRegion.x; final int ymin = destRegion.y; final int xmax = destRegion.width + xmin; final int ymax = destRegion.height + ymin; for (int zi = 0; zi < numDstBands; zi++) { // final int srcBand = (srcBands == null) ? zi : srcBands[zi]; final int dstBand = (dstBands == null) ? zi : dstBands[zi]; final Array array; try { // TODO leak through array = wrapper.variableDS.read(section); } catch (InvalidRangeException e) { throw netcdfFailure(e); } if (flipYAxis) { final IndexIterator it = array.getIndexIterator(); for (int y = ymax; --y >= ymin;) { for (int x = xmin; x < xmax; x++) { switch (type) { case DataBuffer.TYPE_DOUBLE: { raster.setSample(x, y, dstBand, it.getDoubleNext()); break; } case DataBuffer.TYPE_FLOAT: { raster.setSample(x, y, dstBand, it.getFloatNext()); break; } case DataBuffer.TYPE_BYTE: { byte b = it.getByteNext(); // int myByte = (0x000000FF & ((int) b)); // short anUnsignedByte = (short) myByte; // raster.setSample(x, y, dstBand, anUnsignedByte); raster.setSample(x, y, dstBand, b); break; } default: { raster.setSample(x, y, dstBand, it.getIntNext()); break; } } } } } else { switch (type) { case DataBuffer.TYPE_DOUBLE: { DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer(); double[] samples = new double[destRegion.width * destRegion.height]; doubleBuffer.get(samples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples); break; } case DataBuffer.TYPE_FLOAT: float[] samples = new float[destRegion.width * destRegion.height]; FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer(); floatBuffer.get(samples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples); break; case DataBuffer.TYPE_BYTE: //THIS ONLY WORKS FOR ONE BAND!! raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height, array.getDataAsByteBuffer().array()); break; case DataBuffer.TYPE_INT: IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer(); int[] intSamples = new int[destRegion.width * destRegion.height]; intBuffer.get(intSamples); raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples); break; default: { final IndexIterator it = array.getIndexIterator(); for (int y = ymin; y < ymax; y++) { for (int x = xmin; x < xmax; x++) { raster.setSample(x, y, dstBand, it.getIntNext()); } } break; } } } /* * Checks for abort requests after reading. It would be a waste of a * potentially good image (maybe the abort request occurred after we * just finished the reading) if we didn't implemented the * 'isCancel()' method. But because of the later, which is checked * by the NetCDF library, we can't assume that the image is * complete. */ if (abortRequested()) { processReadAborted(); return image; } /* * Reports progress here, not in the deeper loop, because the costly * part is the call to 'variable.read(...)' which can't report * progress. The loop that copy pixel values is fast, so reporting * progress there would be pointless. */ processImageProgress(zi * toPercent); } processImageComplete(); return image; }
From source file:org.mrgeo.data.raster.RasterWritable.java
private static Raster read(final byte[] rasterBytes, Writable payload) throws IOException { WritableRaster raster;//from ww w .j ava 2s . c o 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; }