List of usage examples for java.awt.image ComponentColorModel ComponentColorModel
public ComponentColorModel(ColorSpace colorSpace, boolean hasAlpha, boolean isAlphaPremultiplied, int transparency, int transferType)
From source file:org.photovault.dcraw.DCRawReaderOp.java
public DCRawReaderOp(File f, RenderingHints hints) { super(null, hints, null, 1, 1, 1, 1); file = f;// w ww .j av a 2 s. c o m lrd = lr.libraw_init(0); lrd.output_params.half_size = 1; lr.libraw_open_file(lrd, f.getAbsolutePath()); sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, lrd.sizes.width, lrd.sizes.height, 1, lrd.sizes.width, new int[] { 0 }); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorModel c = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT); ImageLayout il = new ImageLayout(0, 0, 256, 256, sampleModel, c); setImageLayout(il); minX = 0; minY = 0; width = lrd.sizes.width; height = lrd.sizes.height; bayerfilter = lrd.idata.filters; cam_mul = lrd.color.cam_mul; setProperty("bayerfilter", lrd.idata.filters); setProperty("dcraw_cam_mul", cam_mul); setProperty("dcraw_cam_xyz", lrd.color.cam_xyz); setProperty("dcraw_rgb_cam", lrd.color.rgb_cam); setProperty("dcraw_black", lrd.color.black); setProperty("dcraw_max", lrd.color.maximum); setProperty("dcraw_black", lrd.color.black); setProperty("dcraw_margin_top", lrd.sizes.top_margin); setProperty("dcraw_margin_left", lrd.sizes.left_margin); }
From source file:org.photovault.dcraw.AHDInterpolateOp.java
static private ImageLayout layoutHelper(RenderedImage src, int downSample) { int width = src.getWidth() / downSample; int height = src.getHeight() / downSample; PixelInterleavedSampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, width, height, 3, width * 3, new int[] { 0, 1, 2 }); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB); ColorModel c = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT); ImageLayout il = new ImageLayout(0, 0, 256, 256, sampleModel, c); il.setWidth(width);/*from www .j a va 2 s. c om*/ il.setHeight(height); return il; }
From source file:org.apache.pdfbox.pdmodel.graphics.shading.ShadingContext.java
/** * Constructor./* w w w .java2 s . c o m*/ * * @param shading the shading type to be used * @param cm the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream * @throws java.io.IOException if there is an error getting the color space * or doing background color conversion. */ public ShadingContext(PDShading shading, ColorModel cm, AffineTransform xform, Matrix matrix) throws IOException { this.shading = shading; shadingColorSpace = shading.getColorSpace(); // create the output color model using RGB+alpha as color space ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB); outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); bboxRect = shading.getBBox(); if (bboxRect != null) { transformBBox(matrix, xform); } // get background values if available COSArray bg = shading.getBackground(); if (bg != null) { background = bg.toFloatArray(); rgbBackground = convertToRGB(background); } }
From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java
private void createImageStream(PDDocument doc, BufferedImage bi) throws IOException { BufferedImage alphaImage = null; BufferedImage rgbImage = null; int width = bi.getWidth(); int height = bi.getHeight(); if (bi.getColorModel().hasAlpha()) { // extract the alpha information WritableRaster alphaRaster = bi.getAlphaRaster(); ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); alphaImage = new BufferedImage(cm, alphaRaster, false, null); // create a RGB image without alpha rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = rgbImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.drawImage(bi, 0, 0, null);// w ww . jav a2 s . c o m } else { rgbImage = bi; } java.io.OutputStream os = null; try { int numberOfComponents = rgbImage.getColorModel().getNumComponents(); if (numberOfComponents == 3) { setColorSpace(PDDeviceRGB.INSTANCE); } else { if (numberOfComponents == 1) { setColorSpace(new PDDeviceGray()); } else { throw new IllegalStateException(); } } byte[] outData = new byte[width * height * numberOfComponents]; rgbImage.getData().getDataElements(0, 0, width, height, outData); // add FlateDecode compression getPDStream().addCompression(); os = getCOSStream().createUnfilteredStream(); os.write(outData); COSDictionary dic = getCOSStream(); dic.setItem(COSName.FILTER, COSName.FLATE_DECODE); dic.setItem(COSName.SUBTYPE, COSName.IMAGE); dic.setItem(COSName.TYPE, COSName.XOBJECT); if (alphaImage != null) { PDPixelMap smask = new PDPixelMap(doc, alphaImage); dic.setItem(COSName.SMASK, smask); } setBitsPerComponent(8); setHeight(height); setWidth(width); } finally { os.close(); } }
From source file:org.apache.pdfbox.rendering.TilingPaint.java
/** * Returns the pattern image in parent stream coordinates. *//*from www . ja v a2 s. c om*/ private BufferedImage getImage(PageDrawer drawer, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, AffineTransform xform, Rectangle2D anchorRect) throws IOException { ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); float width = (float) Math.abs(anchorRect.getWidth()); float height = (float) Math.abs(anchorRect.getHeight()); // device scale transform (i.e. DPI) (see PDFBOX-1466.pdf) Matrix xformMatrix = new Matrix(xform); float xScale = Math.abs(xformMatrix.getScalingFactorX()); float yScale = Math.abs(xformMatrix.getScalingFactorY()); width *= xScale; height *= yScale; int rasterWidth = Math.max(1, ceiling(width)); int rasterHeight = Math.max(1, ceiling(height)); // create raster WritableRaster raster = cm.createCompatibleWritableRaster(rasterWidth, rasterHeight); BufferedImage image = new BufferedImage(cm, raster, false, null); Graphics2D graphics = image.createGraphics(); // flip a -ve YStep around its own axis (see gs-bugzilla694385.pdf) if (pattern.getYStep() < 0) { graphics.translate(0, rasterHeight); graphics.scale(1, -1); } // flip a -ve XStep around its own axis if (pattern.getXStep() < 0) { graphics.translate(rasterWidth, 0); graphics.scale(-1, 1); } // device scale transform (i.e. DPI) graphics.scale(xScale, yScale); // apply only the scaling from the pattern transform, doing scaling here improves the // image quality and prevents large scale-down factors from creating huge tiling cells. Matrix newPatternMatrix; newPatternMatrix = Matrix.getScaleInstance(Math.abs(patternMatrix.getScalingFactorX()), Math.abs(patternMatrix.getScalingFactorY())); // move origin to (0,0) newPatternMatrix.concatenate(Matrix.getTranslateInstance(-pattern.getBBox().getLowerLeftX(), -pattern.getBBox().getLowerLeftY())); // render using PageDrawer drawer.drawTilingPattern(graphics, pattern, colorSpace, color, newPatternMatrix); graphics.dispose(); return image; }
From source file:org.apache.xmlgraphics.image.loader.impl.PNGFile.java
public ImageRawPNG getImageRawPNG(final ImageInfo info) throws ImageException, IOException { try (final InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec))) { switch (this.colorType) { case PNG_COLOR_GRAY: if (this.hasPalette) { throw new ImageException("Corrupt PNG: color palette is not allowed!"); }//ww w . j a va 2 s .com this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); break; case PNG_COLOR_RGB: // actually a check of the sRGB chunk would be necessary to // confirm // if it's really sRGB this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); break; case PNG_COLOR_PALETTE: if (this.hasAlphaPalette) { this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette, this.bluePalette, this.alphaPalette); } else { this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette, this.bluePalette); } break; case PNG_COLOR_GRAY_ALPHA: if (this.hasPalette) { throw new ImageException("Corrupt PNG: color palette is not allowed!"); } this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); break; case PNG_COLOR_RGB_ALPHA: // actually a check of the sRGB chunk would be necessary to // confirm // if it's really sRGB this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); break; default: throw new ImageException("Unsupported color type: " + this.colorType); } // the iccProfile is still null for now final ImageRawPNG rawImage = new ImageRawPNG(info, seqStream, this.colorModel, this.bitDepth, this.iccProfile); if (this.isTransparent) { if (this.colorType == PNG_COLOR_GRAY) { rawImage.setGrayTransparentAlpha(this.grayTransparentAlpha); } else if (this.colorType == PNG_COLOR_RGB) { rawImage.setRGBTransparentAlpha(this.redTransparentAlpha, this.greenTransparentAlpha, this.blueTransparentAlpha); } else if (this.colorType == PNG_COLOR_PALETTE) { rawImage.setTransparent(); } else { // } } return rawImage; } }
From source file:com.alvermont.terraj.planet.io.ImageBuilder.java
/** * Create and return a <code>BufferedImage</code> object from the * result of the projection. This image can then be further processed * or written out to a file using <code>ImageIO</code>. * * @param proj The projection that will provide the image * @return A <code>BufferedImage</code> object containing the results of * the projection.//from w w w. jav a2 s . com */ public BufferedImage getImage(Projector proj) { // get the pixel data and store it into a data buffer final byte[] pixels = getPixels(proj); final DataBuffer db = new DataBufferByte(pixels, pixels.length); // set up offsets for the R,G,B elements final int[] offsets = new int[3]; offsets[0] = 0; offsets[1] = 1; offsets[2] = 2; // create the raster from the pixel data final int height = proj.getParameters().getProjectionParameters().getHeight(); final int width = proj.getParameters().getProjectionParameters().getWidth(); final WritableRaster raster = Raster.createInterleavedRaster(db, width, height, width * 3, 3, offsets, null); // create a colour model that matches the raster we have final ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); // combine raster and colour model into a buffered image final BufferedImage img = new BufferedImage(cm, raster, false, null); return img; }
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 .ja va 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.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java
/** * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are * converted, other images are left untouched. * * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either, * so we have to convert raster data to a JPG with RGB color space. * * The technique used in this method is due to Mark Stephens, and free for any use. See * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html * * @param is the image data//ww w. ja v a2s. co m * @param colorModel the color model of the image * @return the RGB version of the supplied image */ public static InputStream convertToRGB(InputStream is, ColorModel colorModel) throws IOException, UnsupportedImageException { if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) { return is; } // Get an ImageReader. ImageInputStream input = ImageIO.createImageInputStream(is); try { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers == null || !readers.hasNext()) { throw new UnsupportedImageException("No ImageReaders found"); } ImageReader reader = readers.next(); reader.setInput(input); Raster raster = reader.readRaster(0, reader.getDefaultReadParam()); int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; switch (colorModel) { case YCCK: { float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } break; } case CMYK: { int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null); int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null); int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null); int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null); for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) { int c = 255 - C[i]; int m = 255 - M[i]; int y = 255 - Y[i]; int k = 255 - K[i]; float kk = k / 255f; rgb[base] = (byte) (255 - Math.min(255f, c * kk + k)); rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k)); rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k)); } break; } } // from other image types we know InterleavedRaster's can be // manipulated by AffineTransformOp, so create one of those. raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[] { 0, 1, 2 }, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(convertedImage, "jpg", os); return new ByteArrayInputStream(os.toByteArray()); } finally { IOUtils.closeQuietly(is); if (input != null) { input.close(); } } }
From source file:org.freecine.filmscan.ScanStrip.java
/** Load the scan strip image from disk/*www . j a v a2 s .co m*/ */ private void loadImage() { ImageReader reader; try { // PlanarImage img = JAI.create( "fileload", fname ); ImageInputStream istrm = new FileImageInputStream(file); reader = ImageIO.getImageReadersByFormatName("TIFF").next(); reader.setInput(istrm); ImageReadParam param = reader.getDefaultReadParam(); /* Set the color mode to linear sRGB as we don't have a better profile for the scanner/film available */ ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB); ImageLayout layout = new ImageLayout(); ColorModel cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT); layout.setColorModel(cm); RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); stripImage = ImageReadDescriptor.create(istrm, 0, false, false, false, null, null, param, reader, hints); System.out.println("Color model " + stripImage.getColorModel()); // BufferedImage inImg = reader.read( 0, param ); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); log.error("Strip file " + file + " not found", ex); } catch (IOException ex) { log.error("IO error reading strip " + file + ": ", ex); } }