Example usage for java.awt.image ColorModel getTransferType

List of usage examples for java.awt.image ColorModel getTransferType

Introduction

In this page you can find the example usage for java.awt.image ColorModel getTransferType.

Prototype

public final int getTransferType() 

Source Link

Document

Returns the transfer type of this ColorModel .

Usage

From source file:BlendCompositeDemo.java

private static boolean checkComponentsOrder(ColorModel cm) {
    if (cm instanceof DirectColorModel && cm.getTransferType() == DataBuffer.TYPE_INT) {
        DirectColorModel directCM = (DirectColorModel) cm;

        return directCM.getRedMask() == 0x00FF0000 && directCM.getGreenMask() == 0x0000FF00
                && directCM.getBlueMask() == 0x000000FF
                && (directCM.getNumComponents() != 4 || directCM.getAlphaMask() == 0xFF000000);
    }//  www .  j a  v  a2  s .  c  o m

    return false;
}

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}/*  w ww  .j a v a 2  s  . 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.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  av  a2 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.photovault.image.PhotovaultImage.java

/**
 Add saturation mapping into from of the image processing pipeline.
 @param src The image to which saturation correction is applied
 @return Saturation change operator./*from w  w  w.  j ava 2  s. co  m*/
 */
protected RenderableOp getSaturated(RenderableOp src) {
    IHSColorSpace ihs = IHSColorSpace.getInstance();
    ColorModel srcCm = getCorrectedImageColorModel();
    int[] componentSizes = srcCm.getComponentSize();
    if (componentSizes.length != 3) {
        // This is not an RGB image
        // TODO: handle also images with alpha channel
        return null;
    }
    ColorModel ihsColorModel = new ComponentColorModel(ihs, componentSizes, false, false, Transparency.OPAQUE,
            srcCm.getTransferType());

    // Create a ParameterBlock for the conversion.
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(src);
    pb.add(ihsColorModel);
    // Do the conversion.
    RenderableOp ihsImage = JAI.createRenderable("colorconvert", pb);
    ihsImage.setProperty("org.photovault.opname", "color_corrected_ihs_image");

    //        saturatedIhsImage =
    //                MultiplyConstDescriptor.createRenderable( ihsImage, new double[] {1.0, 1.0, saturation}, null );
    LookupTableJAI jailut = createSaturationMappingLUT();
    saturatedIhsImage = LookupDescriptor.createRenderable(ihsImage, jailut, null);
    saturatedIhsImage.setProperty("org.photovault.opname", "saturated_ihs_image");
    pb = new ParameterBlock();
    pb.addSource(saturatedIhsImage);
    ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel srgbColorModel = new ComponentColorModel(sRGB, componentSizes, false, false, Transparency.OPAQUE,
            srcCm.getTransferType());
    pb.add(srgbColorModel); // RGB color model!        
    RenderableOp saturatedImage = JAI.createRenderable("colorconvert", pb);
    saturatedImage.setProperty("org.photovault.opname", "saturated_image");

    return saturatedImage;
}