List of usage examples for java.awt.image ColorModel isAlphaPremultiplied
boolean isAlphaPremultiplied
To view the source code for java.awt.image ColorModel isAlphaPremultiplied.
Click Source Link
From source file:net.pms.util.GenericIcons.java
/** * Add the format(container) name of the media to the generic icon image. * * @param image BufferdImage to be the label added * @param label the media container name to be added as a label * @param renderer the renderer configuration * * @return the generic icon with the container label added and scaled in accordance with renderer setting *//*from w w w .j av a 2 s . c om*/ private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType) throws IOException { BufferedImage image; switch (iconType) { case AUDIO: image = genericAudioIcon; break; case IMAGE: image = genericImageIcon; break; case VIDEO: image = genericVideoIcon; break; default: image = genericUnknownIcon; } if (image != null) { // Make a copy ColorModel colorModel = image.getColorModel(); image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null); } ByteArrayOutputStream out = null; if (label != null && image != null) { out = new ByteArrayOutputStream(); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); try { int size = 40; Font font = new Font(Font.SANS_SERIF, Font.BOLD, size); FontMetrics metrics = g.getFontMetrics(font); while (size > 7 && metrics.stringWidth(label) > 135) { size--; font = new Font(Font.SANS_SERIF, Font.BOLD, size); metrics = g.getFontMetrics(font); } // Text center point 127x, 49y - calculate centering coordinates int x = 127 - metrics.stringWidth(label) / 2; int y = 46 + metrics.getAscent() / 2; g.drawImage(image, 0, 0, null); g.setColor(Color.WHITE); g.setFont(font); g.drawString(label, x, y); ImageIO.setUseCache(false); ImageIOTools.imageIOWrite(image, imageFormat.toString(), out); } finally { g.dispose(); } } return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false) : null; }
From source file:com.github.dactiv.fear.service.service.account.AccountService.java
/** * ??//from w ww . ja v a2 s . c o m * * @param sourcePath ? * @param targetPath ?? * @param portraitSize ? * * @throws IOException */ private String scaleImage(String sourcePath, String targetPath, PortraitSize portraitSize) throws IOException { InputStream inputStream = new FileInputStream(sourcePath); BufferedImage source = ImageIO.read(inputStream); ColorModel targetColorModel = source.getColorModel(); inputStream.close(); int width = portraitSize.getWidth(); int height = portraitSize.getHeight(); BufferedImage target = new BufferedImage(targetColorModel, targetColorModel.createCompatibleWritableRaster(width, height), targetColorModel.isAlphaPremultiplied(), null); Image scaleImage = source.getScaledInstance(width, height, Image.SCALE_SMOOTH); Graphics2D g = target.createGraphics(); g.drawImage(scaleImage, 0, 0, width, height, null); g.dispose(); String result = targetPath + portraitSize.getName(); FileOutputStream fileOutputStream = new FileOutputStream(result); ImageIO.write(target, PORTRAIT_PIC_TYPE, fileOutputStream); fileOutputStream.close(); return result; }
From source file:ImageOpByRomain.java
/** * {@inheritDoc}//from w w w . j a va 2 s . co m */ public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) { if (destCM == null) { destCM = src.getColorModel(); } return new BufferedImage(destCM, destCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), destCM.isAlphaPremultiplied(), null); }
From source file:lucee.runtime.img.Image.java
public void rotate(float x, float y, float angle, int interpolation) throws ExpressionException { if (x == -1)/*from w ww . ja v a2s . c o m*/ x = (float) getWidth() / 2; if (y == -1) y = (float) getHeight() / 2; angle = (float) Math.toRadians(angle); ColorModel cmSource = image().getColorModel(); if (cmSource instanceof IndexColorModel && cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) { image(PaletteToARGB(image())); cmSource = image().getColorModel(); } BufferedImage alpha = null; if (cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) { alpha = getAlpha(image()); image(removeAlpha(image())); } Interpolation interp = Interpolation.getInstance(0); if (INTERPOLATION_BICUBIC == interpolation) interp = Interpolation.getInstance(1); else if (INTERPOLATION_BILINEAR == interpolation) interp = Interpolation.getInstance(2); if (alpha != null) { ParameterBlock params = new ParameterBlock(); params.addSource(alpha); params.add(x); params.add(y); params.add(angle); params.add(interp); params.add(new double[] { 0.0 }); RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, (RenderingHints.VALUE_INTERPOLATION_BICUBIC)); hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, new BorderExtenderConstant(new double[] { 255.0 }))); hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE)); alpha = JAI.create("rotate", params, hints).getAsBufferedImage(); } ParameterBlock params = new ParameterBlock(); params.addSource(image()); params.add(x); params.add(y); params.add(angle); params.add(interp); params.add(new double[] { 0.0 }); BorderExtender extender = new BorderExtenderConstant(new double[] { 0.0 }); RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender); hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE)); image(JAI.create("rotate", params, hints).getAsBufferedImage()); if (alpha != null) image(addAlpha(image(), alpha, 0, 0)); }
From source file:lucee.runtime.img.Image.java
public Struct info() throws ExpressionException { if (sctInfo != null) return sctInfo; Struct sctInfo = new StructImpl(), sct; sctInfo.setEL("height", new Double(getHeight())); sctInfo.setEL("width", new Double(getWidth())); sctInfo.setEL("source", source == null ? "" : source.getAbsolutePath()); //sct.setEL("mime_type",getMimeType()); ColorModel cm = image().getColorModel(); sct = new StructImpl(); sctInfo.setEL("colormodel", sct); sct.setEL("alpha_channel_support", Caster.toBoolean(cm.hasAlpha())); sct.setEL("alpha_premultiplied", Caster.toBoolean(cm.isAlphaPremultiplied())); sct.setEL("transparency", toStringTransparency(cm.getTransparency())); sct.setEL("pixel_size", Caster.toDouble(cm.getPixelSize())); sct.setEL("num_components", Caster.toDouble(cm.getNumComponents())); sct.setEL("num_color_components", Caster.toDouble(cm.getNumColorComponents())); sct.setEL("colorspace", toStringColorSpace(cm.getColorSpace())); //bits_component int[] bitspercomponent = cm.getComponentSize(); Array arr = new ArrayImpl(); Double value;//from w w w.j a v a 2s . co m for (int i = 0; i < bitspercomponent.length; i++) { sct.setEL("bits_component_" + (i + 1), value = new Double(bitspercomponent[i])); arr.appendEL(value); } sct.setEL("bits_component", arr); // colormodel_type if (cm instanceof ComponentColorModel) sct.setEL("colormodel_type", "ComponentColorModel"); else if (cm instanceof IndexColorModel) sct.setEL("colormodel_type", "IndexColorModel"); else if (cm instanceof PackedColorModel) sct.setEL("colormodel_type", "PackedColorModel"); else sct.setEL("colormodel_type", ListUtil.last(cm.getClass().getName(), '.')); getMetaData(sctInfo); ImageMeta.addInfo(format, source, sctInfo); this.sctInfo = sctInfo; return sctInfo; }
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 {// ww w.j av a2 s . co m 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.geoserver.wps.gs.raster.algebra.JiffleScriptProcessTest.java
@Test public void testOnAllBands() throws Exception { if (testCoverage3 != null) { // Script selection String script = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_PATH)); // Process calculation List<String> scripts = new ArrayList<String>(1); scripts.add(script);//from w w w. j a v a 2 s . c o m GridCoverage2D finalCoverage = process2.execute(testCoverage3, scripts); // Check the result assertNotNull(finalCoverage); RenderedImage finalImage = finalCoverage.getRenderedImage(); // Check on the number of bands int numBandsOut = finalImage.getSampleModel().getNumBands(); int numBandsIn = testCoverage3.getRenderedImage().getSampleModel().getNumBands(); ColorModel cm = testCoverage3.getRenderedImage().getColorModel(); if (cm.hasAlpha() && !cm.isAlphaPremultiplied()) { numBandsIn--; } assertEquals(numBandsIn, numBandsOut); PlanarImage.wrapRenderedImage(finalImage).getTiles(); int[] values = new int[] { MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_0 }; checkExecution(finalImage, values, testCoverage3); finalCoverage.dispose(true); if (finalImage instanceof RenderedOp) { ((RenderedOp) finalImage).dispose(); } } else { LOGGER.log(Level.WARNING, "\nTest5: file " + IMAGE_NAME_3 + " not found in geoserver-enterprise/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/raster/algebra"); } }
From source file:org.geoserver.wps.gs.raster.algebra.JiffleScriptProcessTest.java
@Test public void testOnAllBandsMultiScripts() throws Exception { if (testCoverage3 != null) { // Script1 selection String script = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_PATH)); // Script2 selection String script2 = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_2_PATH)); // Process calculation List<String> scripts = new ArrayList<String>(1); scripts.add(script);/* ww w. jav a 2 s.co m*/ scripts.add(script2); scripts.add(script2); GridCoverage2D finalCoverage = process2.execute(testCoverage3, scripts); // Check the result assertNotNull(finalCoverage); RenderedImage finalImage = finalCoverage.getRenderedImage(); // Check on the number of bands int numBandsOut = finalImage.getSampleModel().getNumBands(); int numBandsIn = testCoverage3.getRenderedImage().getSampleModel().getNumBands(); ColorModel cm = testCoverage3.getRenderedImage().getColorModel(); if (cm != null && cm instanceof ComponentColorModel && cm.hasAlpha() && !cm.isAlphaPremultiplied()) { numBandsIn--; } assertEquals(numBandsIn, numBandsOut); PlanarImage.wrapRenderedImage(finalImage).getTiles(); int[] values = new int[] { MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_1, MORE_THAN_ZERO_BAND_1 }; checkExecution(finalImage, values, testCoverage3); finalCoverage.dispose(true); if (finalImage instanceof RenderedOp) { ((RenderedOp) finalImage).dispose(); } } else { LOGGER.log(Level.WARNING, "\nTest6: file " + IMAGE_NAME_3 + " not found in geoserver-enterprise/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/raster/algebra"); } }
From source file:org.geotools.imageio.netcdf.NetCDFImageReader.java
/** * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam) *///from w ww .j a va2 s . com @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 v a 2s.c o m @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; }