List of usage examples for java.awt.image ColorModel getNumComponents
public int getNumComponents()
From source file:omr.jai.TestImage3.java
public static void print(PlanarImage pi) { // Show the image dimensions and coordinates. System.out.print("Image Dimensions: "); System.out.print(pi.getWidth() + "x" + pi.getHeight() + " pixels"); // Remember getMaxX and getMaxY return the coordinate of the next point! System.out.println(" (from " + pi.getMinX() + "," + pi.getMinY() + " to " + (pi.getMaxX() - 1) + "," + (pi.getMaxY() - 1) + ")"); if ((pi.getNumXTiles() != 1) || (pi.getNumYTiles() != 1)) { // Is it tiled? // Tiles number, dimensions and coordinates. System.out.print("Tiles: "); System.out.print(pi.getTileWidth() + "x" + pi.getTileHeight() + " pixels" + " (" + pi.getNumXTiles() + "x" + pi.getNumYTiles() + " tiles)"); System.out.print(" (from " + pi.getMinTileX() + "," + pi.getMinTileY() + " to " + pi.getMaxTileX() + "," + pi.getMaxTileY() + ")"); System.out.println(" offset: " + pi.getTileGridXOffset() + "," + pi.getTileGridXOffset()); }/* ww w. j a v a 2s .co m*/ // Display info about the SampleModel of the image. SampleModel sm = pi.getSampleModel(); System.out.println("Number of bands: " + sm.getNumBands()); System.out.print("Data type: "); switch (sm.getDataType()) { case DataBuffer.TYPE_BYTE: System.out.println("byte"); break; case DataBuffer.TYPE_SHORT: System.out.println("short"); break; case DataBuffer.TYPE_USHORT: System.out.println("ushort"); break; case DataBuffer.TYPE_INT: System.out.println("int"); break; case DataBuffer.TYPE_FLOAT: System.out.println("float"); break; case DataBuffer.TYPE_DOUBLE: System.out.println("double"); break; case DataBuffer.TYPE_UNDEFINED: System.out.println("undefined"); break; } // Display info about the ColorModel of the image. ColorModel cm = pi.getColorModel(); if (cm != null) { System.out.println("Number of color components: " + cm.getNumComponents()); System.out.println("Bits per pixel: " + cm.getPixelSize()); System.out.print("Image Transparency: "); switch (cm.getTransparency()) { case Transparency.OPAQUE: System.out.println("opaque"); break; case Transparency.BITMASK: System.out.println("bitmask"); break; case Transparency.TRANSLUCENT: System.out.println("translucent"); break; } } else System.out.println("No color model."); }
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;// w w w. j av a 2 s.c o 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.fop.render.pdf.ImageRawPNGAdapter.java
/** {@inheritDoc} */ public void setup(PDFDocument doc) { super.setup(doc); ColorModel cm = ((ImageRawPNG) this.image).getColorModel(); if (cm instanceof IndexColorModel) { numberOfInterleavedComponents = 1; } else {/*from w w w .ja v a2 s . c o m*/ // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha) // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents(); numberOfInterleavedComponents = cm.getNumComponents(); } // set up image compression for non-alpha channel FlateFilter flate; try { flate = new FlateFilter(); flate.setApplied(true); flate.setPredictor(FlateFilter.PREDICTION_PNG_OPT); if (numberOfInterleavedComponents < 3) { // means palette (1) or gray (1) or gray + alpha (2) flate.setColors(1); } else { // means rgb (3) or rgb + alpha (4) flate.setColors(3); } flate.setColumns(image.getSize().getWidthPx()); flate.setBitsPerComponent(this.getBitsPerComponent()); } catch (PDFFilterException e) { throw new RuntimeException("FlateFilter configuration error", e); } this.pdfFilter = flate; this.disallowMultipleFilters(); // Handle transparency channel if applicable; note that for palette images the transparency is // not TRANSLUCENT if (cm.hasAlpha() && cm.getTransparency() == ColorModel.TRANSLUCENT) { doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI()); // TODO: Implement code to combine image with background color if transparency is not allowed // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha channel // and then deflate it back again ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater()); InputStream in = ((ImageRawStream) image).createInputStream(); try { InflaterInputStream infStream = new InflaterInputStream(in, new Inflater()); DataInputStream dataStream = new DataInputStream(infStream); // offset is the byte offset of the alpha component int offset = numberOfInterleavedComponents - 1; // 1 for GA, 3 for RGBA int numColumns = image.getSize().getWidthPx(); int bytesPerRow = numberOfInterleavedComponents * numColumns; int filter; // read line by line; the first byte holds the filter while ((filter = dataStream.read()) != -1) { byte[] bytes = new byte[bytesPerRow]; dataStream.readFully(bytes, 0, bytesPerRow); dos.write((byte) filter); for (int j = 0; j < numColumns; j++) { dos.write(bytes, offset, 1); offset += numberOfInterleavedComponents; } offset = numberOfInterleavedComponents - 1; } dos.close(); } catch (IOException e) { throw new RuntimeException("Error processing transparency channel:", e); } finally { IOUtils.closeQuietly(in); } // set up alpha channel compression FlateFilter transFlate; try { transFlate = new FlateFilter(); transFlate.setApplied(true); transFlate.setPredictor(FlateFilter.PREDICTION_PNG_OPT); transFlate.setColors(1); transFlate.setColumns(image.getSize().getWidthPx()); transFlate.setBitsPerComponent(this.getBitsPerComponent()); } catch (PDFFilterException e) { throw new RuntimeException("FlateFilter configuration error", e); } BitmapImage alphaMask = new BitmapImage("Mask:" + this.getKey(), image.getSize().getWidthPx(), image.getSize().getHeightPx(), baos.toByteArray(), null); alphaMask.setPDFFilter(transFlate); alphaMask.disallowMultipleFilters(); alphaMask.setColorSpace(new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_GRAY)); softMask = doc.addImage(null, alphaMask).makeReference(); } }
From source file:org.apache.fop.render.ps.ImageEncoderPNG.java
/** * Main constructor// w w w.ja va 2s . c o m * @param image the PNG image */ public ImageEncoderPNG(ImageRawPNG image) { this.image = image; ColorModel cm = ((ImageRawPNG) this.image).getColorModel(); if (cm instanceof IndexColorModel) { numberOfInterleavedComponents = 1; } else { // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha) // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents(); numberOfInterleavedComponents = cm.getNumComponents(); } }
From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java
/** * Returns a {@link java.awt.image.BufferedImage} of the COSStream * set in the constructor or null if the COSStream could not be encoded. * * @return {@inheritDoc}//from w ww . j av a 2s . c om * * @throws IOException {@inheritDoc} */ public BufferedImage getRGBImage() throws IOException { if (image != null) { return image; } try { int width = getWidth(); int height = getHeight(); int bpc = getBitsPerComponent(); byte[] array = getPDStream().getByteArray(); if (array.length == 0) { LOG.error("Something went wrong ... the pixelmap doesn't contain any data."); return null; } // Get the ColorModel right PDColorSpace colorspace = getColorSpace(); if (colorspace == null) { LOG.error("getColorSpace() returned NULL. Predictor = " + getPredictor()); return null; } ColorModel cm = null; if (colorspace instanceof PDIndexed) { PDIndexed csIndexed = (PDIndexed) colorspace; // the base color space uses 8 bit per component, as the indexed color values // of an indexed color space are always in a range from 0 to 255 ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8); // number of possible color values in the target color space int numberOfColorValues = 1 << bpc; // number of indexed color values int highValue = csIndexed.getHighValue(); // choose the correct size, sometimes there are more indexed values than needed // and sometimes there are fewer indexed value than possible int size = Math.min(numberOfColorValues - 1, highValue); byte[] index = csIndexed.getLookupData(); boolean hasAlpha = baseColorModel.hasAlpha(); COSBase maskArray = getMask(); if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) { throw new IOException("Not implemented"); } // the IndexColorModel uses RGB-based color values // which leads to 3 color components and a optional alpha channel int numberOfComponents = 3 + (hasAlpha ? 1 : 0); int buffersize = (size + 1) * numberOfComponents; byte[] colorValues = new byte[buffersize]; byte[] inData = new byte[baseColorModel.getNumComponents()]; int bufferIndex = 0; for (int i = 0; i <= size; i++) { System.arraycopy(index, i * inData.length, inData, 0, inData.length); // convert the indexed color values to RGB colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData); colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData); colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData); if (hasAlpha) { colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData); } bufferIndex += numberOfComponents; } if (maskArray != null && maskArray instanceof COSArray) { cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha, ((COSArray) maskArray).getInt(0)); } else { cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha); } } else if (colorspace instanceof PDSeparation) { PDSeparation csSeparation = (PDSeparation) colorspace; int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents(); PDFunction tintTransformFunc = csSeparation.getTintTransform(); COSArray decode = getDecode(); // we have to invert the tint-values, // if the Decode array exists and consists of (1,0) boolean invert = decode != null && decode.getInt(0) == 1; // TODO add interpolation for other decode values then 1,0 int maxValue = (int) Math.pow(2, bpc) - 1; // destination array byte[] mappedData = new byte[width * height * numberOfComponents]; int rowLength = width * numberOfComponents; float[] input = new float[1]; for (int i = 0; i < height; i++) { int rowOffset = i * rowLength; for (int j = 0; j < width; j++) { // scale tint values to a range of 0...1 int value = (array[i * width + j] + 256) % 256; if (invert) { input[0] = 1 - (value / maxValue); } else { input[0] = value / maxValue; } float[] mappedColor = tintTransformFunc.eval(input); int columnOffset = j * numberOfComponents; for (int k = 0; k < numberOfComponents; k++) { // redo scaling for every single color value float mappedValue = mappedColor[k]; mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue); } } } array = mappedData; cm = colorspace.createColorModel(bpc); } else if (bpc == 1) { byte[] map = null; if (colorspace instanceof PDDeviceGray) { COSArray decode = getDecode(); // we have to invert the b/w-values, // if the Decode array exists and consists of (1,0) if (decode != null && decode.getInt(0) == 1) { map = new byte[] { (byte) 0xff }; } else { map = new byte[] { (byte) 0x00, (byte) 0xff }; } } else if (colorspace instanceof PDICCBased) { if (((PDICCBased) colorspace).getNumberOfComponents() == 1) { map = new byte[] { (byte) 0xff }; } else { map = new byte[] { (byte) 0x00, (byte) 0xff }; } } else { map = new byte[] { (byte) 0x00, (byte) 0xff }; } cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE); } else { if (colorspace instanceof PDICCBased) { if (((PDICCBased) colorspace).getNumberOfComponents() == 1) { byte[] map = new byte[] { (byte) 0xff }; cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE); } else { cm = colorspace.createColorModel(bpc); } } else { cm = colorspace.createColorModel(bpc); } } LOG.debug("ColorModel: " + cm.toString()); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer(); byte[] bufferData = buffer.getData(); System.arraycopy(array, 0, bufferData, 0, (array.length < bufferData.length ? array.length : bufferData.length)); image = new BufferedImage(cm, raster, false, null); // If there is a 'soft mask' image then we use that as a transparency mask. PDXObjectImage smask = getSMaskImage(); if (smask != null) { BufferedImage smaskBI = smask.getRGBImage(); COSArray decodeArray = smask.getDecode(); CompositeImage compositeImage = new CompositeImage(image, smaskBI); BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray); return rgbImage; } else if (getImageMask()) { BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = (Graphics2D) stencilMask.getGraphics(); if (getStencilColor() != null) { graphics.setColor(getStencilColor().getJavaColor()); } else { // this might happen when using ExractImages, see PDFBOX-1145 LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead."); graphics.setColor(Color.BLACK); } graphics.fillRect(0, 0, width, height); // assume default values ([0,1]) for the DecodeArray // TODO DecodeArray == [1,0] graphics.setComposite(AlphaComposite.DstIn); graphics.drawImage(image, null, 0, 0); return stencilMask; } else { // if there is no mask, use the unaltered image. return image; } } catch (Exception exception) { LOG.error(exception, exception); //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw. //Returning the NULL falls through to Phillip Koch's TODO section. return null; } }
From source file:org.apache.xmlgraphics.ps.PSImageUtils.java
private static ColorModel populateImageDictionary(ImageEncodingHelper helper, PSDictionary imageDict) { RenderedImage img = helper.getImage(); String w = Integer.toString(img.getWidth()); String h = Integer.toString(img.getHeight()); imageDict.put("/ImageType", "1"); imageDict.put("/Width", w); imageDict.put("/Height", h); ColorModel cm = helper.getEncodedColorModel(); boolean invertColors = false; String decodeArray = getDecodeArray(cm.getNumComponents(), invertColors); int bitsPerComp = cm.getComponentSize(0); // Setup scanning for left-to-right and top-to-bottom imageDict.put("/ImageMatrix", "[" + w + " 0 0 " + h + " 0 0]"); if ((cm instanceof IndexColorModel)) { IndexColorModel im = (IndexColorModel) cm; int c = im.getMapSize(); int hival = c - 1; if (hival > 4095) { throw new UnsupportedOperationException("hival must not go beyond 4095"); }/*from www . ja v a 2s . c o m*/ bitsPerComp = im.getPixelSize(); int ceiling = ((int) Math.pow(2, bitsPerComp)) - 1; decodeArray = "[0 " + ceiling + "]"; } imageDict.put("/BitsPerComponent", Integer.toString(bitsPerComp)); imageDict.put("/Decode", decodeArray); return cm; }
From source file:org.dcm4che3.tool.dcm2jpg.Dcm2Jpg.java
private BufferedImage convert(BufferedImage bi) { ColorModel cm = bi.getColorModel(); return cm.getNumComponents() == 3 ? BufferedImageUtils.convertToIntRGB(bi) : bi; }
From source file:org.geoserver.catalog.CoverageViewReader.java
private int getAlphaBandIndex(GridCoverage2D coverage) { final ColorModel cm = coverage.getRenderedImage().getColorModel(); if (!cm.hasAlpha() || cm.getNumComponents() == cm.getNumColorComponents()) { throw new IllegalArgumentException( "The source coverage does not have an alpha band, cannot extract an alpha band"); }/*from ww w.ja va 2 s .c o m*/ // the alpha band is always the last (see ComponentColorModel.getAlphaRaster or the getAlpha(object) code if (cm.getNumColorComponents() == 1) { // gray-alpha return 1; } else { // rgba/argb return 3; } }
From source file:org.geoserver.catalog.CoverageViewReader.java
private boolean hasAlphaBand(ColorModel cm) { // num components returns the alpha, num _color_ components does not return (cm.getNumComponents() == 2 && cm.getNumColorComponents() == 1) /* gray-alpha case */ || (cm.getNumComponents() == 4 && cm.getNumColorComponents() == 3) /* rgba case */; }
From source file:org.geoserver.wps.gs.GeorectifyCoverage.java
@DescribeResults({ @DescribeResult(name = "result", description = "Georectified raster", type = GridCoverage2D.class), @DescribeResult(name = "path", description = "Pathname of the generated raster on the server", type = String.class) }) public Map<String, Object> execute( @DescribeParameter(name = "data", description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "gcp", description = "List of Ground control points. Points are specified as [x,y] or [x,y,z].") String gcps, @DescribeParameter(name = "bbox", description = "Bounding box for output", min = 0) Envelope bbox, @DescribeParameter(name = "targetCRS", description = "Coordinate reference system to use for the output raster") CoordinateReferenceSystem crs, @DescribeParameter(name = "width", description = "Width of output raster in pixels", min = 0) Integer width, @DescribeParameter(name = "height", description = "Height of output raster in pixels", min = 0) Integer height, @DescribeParameter(name = "warpOrder", min = 0, description = "Order of the warping polynomial (1 to 3)") Integer warpOrder, @DescribeParameter(name = "transparent", min = 0, description = "Force output to have transparent background") Boolean transparent, @DescribeParameter(name = "store", min = 0, description = "Indicates whether to keep the output file after processing") Boolean store, @DescribeParameter(name = "outputPath", min = 0, description = "Pathname where the output file is stored") String outputPath) throws IOException { GeoTiffReader reader = null;/* w ww .ja v a2 s .c o m*/ List<File> removeFiles = new ArrayList<File>(); String location = null; try { File tempFolder = config.getTempFolder(); File loggingFolder = config.getLoggingFolder(); // do we have to add the alpha channel? boolean forceTransparent = false; if (transparent == null) { transparent = true; } ColorModel cm = coverage.getRenderedImage().getColorModel(); if (cm.getTransparency() == Transparency.OPAQUE && transparent) { forceTransparent = true; } // // // // STEP 1: Getting the dataset to be georectified // // // final Object fileSource = coverage.getProperty(GridCoverage2DReader.FILE_SOURCE_PROPERTY); if (fileSource != null && fileSource instanceof String) { location = (String) fileSource; } if (location == null) { RenderedImage image = coverage.getRenderedImage(); if (forceTransparent) { ImageWorker iw = new ImageWorker(image); iw.forceComponentColorModel(); final ImageLayout tempLayout = new ImageLayout(image); tempLayout.unsetValid(ImageLayout.COLOR_MODEL_MASK).unsetValid(ImageLayout.SAMPLE_MODEL_MASK); RenderedImage alpha = ConstantDescriptor.create(Float.valueOf(image.getWidth()), Float.valueOf(image.getHeight()), new Byte[] { Byte.valueOf((byte) 255) }, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, tempLayout)); iw.addBand(alpha, false); image = iw.getRenderedImage(); cm = image.getColorModel(); } File storedImageFile = storeImage(image, tempFolder); location = storedImageFile.getAbsolutePath(); removeFiles.add(storedImageFile); } // // // // STEP 2: Adding Ground Control Points // // // final int gcpNum[] = new int[1]; final String gcp = parseGcps(gcps, gcpNum); File vrtFile = addGroundControlPoints(location, gcp, config.getGdalTranslateParameters()); if (vrtFile == null || !vrtFile.exists() || !vrtFile.canRead()) { throw new IOException("Unable to get a valid file with attached Ground Control Points"); } removeFiles.add(vrtFile); // // // // STEP 3: Warping // // // File warpedFile = warpFile(vrtFile, bbox, crs, width, height, warpOrder, tempFolder, loggingFolder, config.getExecutionTimeout(), config.getGdalWarpingParameters()); if (warpedFile == null || !warpedFile.exists() || !warpedFile.canRead()) { throw new IOException("Unable to get a valid georectified file"); } boolean expand = false; if (cm instanceof IndexColorModel) { expand = true; } else if (cm instanceof ComponentColorModel && cm.getNumComponents() == 1 && cm.getComponentSize()[0] == 1) { expand = true; } if (expand) { removeFiles.add(warpedFile); warpedFile = expandRgba(warpedFile.getAbsolutePath()); } // if we have the output path move the final file there if (Boolean.TRUE.equals(store) && outputPath != null) { File output = new File(outputPath); if (output.exists()) { if (!output.delete()) { throw new WPSException("Output file " + outputPath + " exists but cannot be overwritten"); } } else { File parent = output.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new WPSException("Output file parent directory " + parent.getAbsolutePath() + " does not exist and cannot be created"); } } } if (!warpedFile.renameTo(output)) { throw new WPSException("Could not move " + warpedFile.getAbsolutePath() + " to " + outputPath + ", it's likely a permission issue"); } warpedFile = output; } // mark the output file for deletion at the end of request if (resourceManager != null && !Boolean.TRUE.equals(store)) { resourceManager.addResource(new WPSFileResource(warpedFile)); } // // // // FINAL STEP: Returning the warped gridcoverage // // // reader = new GeoTiffReader(warpedFile); GridCoverage2D cov = addLocationProperty(reader.read(null), warpedFile); Map<String, Object> result = new HashMap<String, Object>(); result.put("result", cov); result.put("path", warpedFile.getAbsolutePath()); return result; } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } for (File file : removeFiles) { deleteFile(file); } } }