List of usage examples for java.awt.image RenderedImage getColorModel
ColorModel getColorModel();
From source file:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java
/** * Cut the quicklook that have a big width/height ratio. * Each sub-part is dispatched on multiple bands. * * @param quick_look the quick_look to be cut * @param max_ratio the maximum ratio between quick_look width and height. * @param margin the margin between each band. default 5. *//*from w w w .jav a 2 s .c om*/ public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) { ColorModel color_model = input_image.getColorModel(); if ((color_model == null) && (input_image.getSampleModel() != null)) { color_model = ColorRenderer.createColorModel(input_image.getSampleModel()); } BufferedImage quick_look; try { quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage( new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model); } catch (Exception e) { logger.error("Problem getting buffered image.", e); throw new IllegalArgumentException("Problem getting buffered image", e); } if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) { //Compute width/height ratio int ql_width = quick_look.getWidth(); int ql_height = quick_look.getHeight(); int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height)); //Check if the quicklook has a strong width/height ratio if ((ratio < max_ratio) || (ratio <= 1)) return PlanarImage.wrapRenderedImage(quick_look); /** * Cut the wider side (width or height) into "ratio" bands. * Ex: If height = 3 * width then we cut 3 bands along columns * So height' = height / 3 (extract 1 band / 3 from height) * width' = width * 3 (dispatch 3 bands along lines) */ int width = ql_width; //width of the bands int height = ql_height; //height of the bands if (ql_width < ql_height) //cut along height { width = (ql_width + margin) * ratio; height = ql_height / ratio; } else //cut along width { width = ql_width / ratio; height = (ql_height + margin) * ratio; } //Dispatch the sub-parts BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = quick_look_cut.createGraphics(); for (int k = 0; k < ratio; k++) { BufferedImage ql_band = null; //Dispatch on columns if (ql_width < ql_height) { ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio); g2.drawImage(ql_band, null, k * (ql_width + margin), 0); } //Dispatch on lines else { ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height); g2.drawImage(ql_band, null, 0, k * (ql_height + margin)); } } //for each band g2.dispose(); return PlanarImage.wrapRenderedImage(quick_look_cut); } return PlanarImage.wrapRenderedImage(quick_look); }
From source file:GraphicsUtil.java
/** * Extracts an alpha raster from a RenderedImage. The method tries to avoid copying data * unnecessarily by checking if the RenderedImage is a BufferedImage which offers suitable * direct methods./*www. j a v a 2 s . co m*/ * @param image the image * @return the alpha raster */ public static Raster getAlphaRaster(RenderedImage image) { ColorModel cm = image.getColorModel(); if (!cm.hasAlpha() || cm.getTransparency() != ColorModel.TRANSLUCENT) { throw new IllegalStateException("Image doesn't have an alpha channel"); } Raster alpha; if (image instanceof BufferedImage) { //Optimization possible with BufferedImage (No copying) alpha = ((BufferedImage) image).getAlphaRaster(); } else { WritableRaster wraster = GraphicsUtil.makeRasterWritable(image.getData()); alpha = image.getColorModel().getAlphaRaster(wraster); } return alpha; }
From source file:com.alibaba.simpleimage.util.ImageLog.java
protected String formatMsg(Object action, RenderedImage img) { String msgFmt = action + ": {0}={1} DataType={2} Width={3} Height={4}"; String clazz = img.getColorModel().getColorSpace().getClass().getSimpleName(); int type = img.getColorModel().getColorSpace().getType(); int dataType = img.getData().getDataBuffer().getDataType(); int w = img.getWidth(); int h = img.getHeight(); String msg = MessageFormat.format(msgFmt, clazz, getColorSpaceName(type), getDataTypeName(dataType), w, h); return msg;/*from ww w . j a va 2 s . c o m*/ }
From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java
/** * Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the * ColorConvert operation fails for unknown reasons ?! * /* ww w . j av a 2 s.c o m*/ * @param img image to convert * @return converted image */ public PlanarImage toDirectColorModel(RenderedImage img) { BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img.getColorModel().isAlphaPremultiplied(), null); ColorConvertOp op = new ColorConvertOp(null); op.filter(source, dest); return PlanarImage.wrapRenderedImage(dest); }
From source file:org.apache.fop.render.pcl.PCLGenerator.java
private RenderedImage getMask(RenderedImage img, Dimension targetDim) { ColorModel cm = img.getColorModel(); if (cm.hasAlpha()) { BufferedImage alpha = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Raster raster = img.getData(); GraphicsUtil.copyBand(raster, cm.getNumColorComponents(), alpha.getRaster(), 0); BufferedImageOp op1 = new LookupOp(new ByteLookupTable(0, THRESHOLD_TABLE), null); BufferedImage alphat = op1.filter(alpha, null); BufferedImage mask;/*from ww w. ja va 2s . c o m*/ if (true) { mask = new BufferedImage(targetDim.width, targetDim.height, BufferedImage.TYPE_BYTE_BINARY); } else { byte[] arr = { (byte) 0, (byte) 0xff }; ColorModel colorModel = new IndexColorModel(1, 2, arr, arr, arr); WritableRaster wraster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, targetDim.width, targetDim.height, 1, 1, null); mask = new BufferedImage(colorModel, wraster, false, null); } Graphics2D g2d = mask.createGraphics(); try { AffineTransform at = new AffineTransform(); double sx = targetDim.getWidth() / img.getWidth(); double sy = targetDim.getHeight() / img.getHeight(); at.scale(sx, sy); g2d.drawRenderedImage(alphat, at); } finally { g2d.dispose(); } /* try { BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png")); BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png")); } catch (IOException e) { e.printStackTrace(); }*/ return mask; } else { return null; } }
From source file:org.apache.fop.render.pcl.PCLGenerator.java
/** * Paint a bitmap at the current cursor position. The bitmap must be a monochrome * (1-bit) bitmap image./*from w w w . j a v a 2 s . co m*/ * @param img the bitmap image (must be 1-bit b/w) * @param resolution the resolution of the image (must be a PCL resolution) * @throws IOException In case of an I/O error */ public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException { if (!isValidPCLResolution(resolution)) { throw new IllegalArgumentException("Invalid PCL resolution: " + resolution); } boolean monochrome = isMonochromeImage(img); if (!monochrome) { throw new IllegalArgumentException("img must be a monochrome image"); } setRasterGraphicsResolution(resolution); writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A"); Raster raster = img.getData(); Encoder encoder = new Encoder(img); // Transfer graphics data int imgw = img.getWidth(); IndexColorModel cm = (IndexColorModel) img.getColorModel(); if (cm.getTransferType() == DataBuffer.TYPE_BYTE) { DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1); if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) { //Optimized packed encoding byte[] buf = dataBuffer.getData(); int scanlineStride = packedSampleModel.getScanlineStride(); int idx = 0; int c0 = toGray(cm.getRGB(0)); int c1 = toGray(cm.getRGB(1)); boolean zeroIsWhite = c0 > c1; for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = scanlineStride; x < maxx; x++) { if (zeroIsWhite) { encoder.add8Bits(buf[idx]); } else { encoder.add8Bits((byte) ~buf[idx]); } idx++; } encoder.endLine(); } } else { //Optimized non-packed encoding for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { byte[] line = (byte[]) raster.getDataElements(0, y, imgw, 1, null); for (int x = 0, maxx = imgw; x < maxx; x++) { encoder.addBit(line[x] == 0); } encoder.endLine(); } } } else { //Safe but slow fallback for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = imgw; x < maxx; x++) { int sample = raster.getSample(x, y, 0); encoder.addBit(sample == 0); } encoder.endLine(); } } // End raster graphics writeCommand("*rB"); }
From source file:org.apache.fop.render.pdf.ImageRenderedAdapter.java
/** {@inheritDoc} */ @Override/* www . j a v a 2 s. co m*/ public void setup(PDFDocument doc) { RenderedImage ri = getImage().getRenderedImage(); super.setup(doc); //Handle transparency mask if applicable ColorModel orgcm = ri.getColorModel(); if (orgcm.hasAlpha() && orgcm.getTransparency() == ColorModel.TRANSLUCENT) { doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI()); //TODO Implement code to combine image with background color if transparency is not //allowed (need BufferedImage support for that) AlphaRasterImage alphaImage = new AlphaRasterImage("Mask:" + getKey(), ri); this.softMask = doc.addImage(null, alphaImage).makeReference(); } }
From source file:org.apache.fop.util.BitmapImageUtilTestCase.java
/** * Tests the convertTo* methods./* w ww .j a v a 2 s . c om*/ * @throws Exception if an error occurs */ @Test public void testConvertToMono() throws Exception { BufferedImage testImage = createTestImage(); saveAsPNG(testImage, "test-image"); RenderedImage img; Dimension scaled = new Dimension(320, 240); img = BitmapImageUtil.convertToGrayscale(testImage, null); saveAsPNG(img, "out-gray"); assertEquals(1, img.getColorModel().getNumComponents()); assertEquals(8, img.getColorModel().getPixelSize()); assertEquals(640, img.getWidth()); assertEquals(480, img.getHeight()); assertPixels("5757575757575757575757FFFFFFFFFF", img, 220, 34, 16); img = BitmapImageUtil.convertToGrayscale(testImage, scaled); saveAsPNG(img, "out-gray-scaled"); assertEquals(1, img.getColorModel().getNumComponents()); assertEquals(8, img.getColorModel().getPixelSize()); assertEquals(320, img.getWidth()); assertEquals(240, img.getHeight()); img = BitmapImageUtil.convertToMonochrome(testImage, null); saveAsPNG(img, "out-mono"); assertEquals(1, img.getColorModel().getPixelSize()); assertEquals(640, img.getWidth()); assertEquals(480, img.getHeight()); assertPixels("00000000000000000000000101010101", img, 220, 34, 16); if (isJAIAvailable()) { img = BitmapImageUtil.convertToMonochrome(testImage, null, 0.5f); saveAsPNG(img, "out-mono-jai-0.5"); assertEquals(1, img.getColorModel().getPixelSize()); assertEquals(640, img.getWidth()); assertEquals(480, img.getHeight()); assertPixels("00010000000100000001000101010101", img, 220, 34, 16); img = BitmapImageUtil.convertToMonochrome(testImage, null, 1.0f); saveAsPNG(img, "out-mono-jai-1.0"); assertEquals(1, img.getColorModel().getPixelSize()); assertEquals(640, img.getWidth()); assertEquals(480, img.getHeight()); assertPixels("01000001000001000001000101010101", img, 220, 34, 16); } }
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 {/*from w ww . j a v a 2 s. c o 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.apache.xmlgraphics.ps.PSImageUtils.java
/** * Extracts a packed RGB integer array of a RenderedImage. * @param img the image//from w w w. java2s . c o m * @param startX the starting X coordinate * @param startY the starting Y coordinate * @param w the width of the cropped image * @param h the height of the cropped image * @param rgbArray the prepared integer array to write to * @param offset offset in the target array * @param scansize width of a row in the target array * @return the populated integer array previously passed in as rgbArray parameter */ public static int[] getRGB(RenderedImage img, int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) { Raster raster = img.getData(); int yoff = offset; int off; Object data; int nbands = raster.getNumBands(); int dataType = raster.getDataBuffer().getDataType(); switch (dataType) { case DataBuffer.TYPE_BYTE: data = new byte[nbands]; break; case DataBuffer.TYPE_USHORT: data = new short[nbands]; break; case DataBuffer.TYPE_INT: data = new int[nbands]; break; case DataBuffer.TYPE_FLOAT: data = new float[nbands]; break; case DataBuffer.TYPE_DOUBLE: data = new double[nbands]; break; default: throw new IllegalArgumentException("Unknown data buffer type: " + dataType); } if (rgbArray == null) { rgbArray = new int[offset + h * scansize]; } ColorModel colorModel = img.getColorModel(); for (int y = startY; y < startY + h; y++, yoff += scansize) { off = yoff; for (int x = startX; x < startX + w; x++) { rgbArray[off++] = colorModel.getRGB(raster.getDataElements(x, y, data)); } } return rgbArray; }