Example usage for java.awt.color ICC_ColorSpace ICC_ColorSpace

List of usage examples for java.awt.color ICC_ColorSpace ICC_ColorSpace

Introduction

In this page you can find the example usage for java.awt.color ICC_ColorSpace ICC_ColorSpace.

Prototype

public ICC_ColorSpace(ICC_Profile profile) 

Source Link

Document

Constructs a new ICC_ColorSpace from an ICC_Profile object.

Usage

From source file:org.apache.pdfbox.pdmodel.graphics.color.PDICCBased.java

/**
 * Create a Java colorspace for this colorspace.
 *
 * @return A color space that can be used for Java AWT operations.
 *
 * @throws IOException If there is an error creating the color space.
 *///w  w  w .j a  v  a2  s  . c o  m
protected ColorSpace createColorSpace() throws IOException {
    InputStream profile = null;
    ColorSpace cSpace = null;
    try {
        profile = stream.createInputStream();
        ICC_Profile iccProfile = ICC_Profile.getInstance(profile);
        cSpace = new ICC_ColorSpace(iccProfile);
        float[] components = new float[numberOfComponents];
        // there maybe a ProfileDataException or a CMMException as there
        // are some issues when loading ICC_Profiles, see PDFBOX-1295
        // Try to create a color as test ...
        new Color(cSpace, components, 1f);
    } catch (RuntimeException e) {
        // we are using an alternate colorspace as fallback
        LOG.debug("Can't read ICC-profile, using alternate colorspace instead");
        List alternateCSList = getAlternateColorSpaces();
        PDColorSpace alternate = (PDColorSpace) alternateCSList.get(0);
        cSpace = alternate.getJavaColorSpace();
    } finally {
        if (profile != null) {
            profile.close();
        }
    }
    return cSpace;
}

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  a v  a 2  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.gmdev.pdftrick.utils.CustomExtraImgReader.java

/**
 * Convert image from Cmyk to Rgb profile
 * @param cmykRaster//from ww w.  j a v a  2 s.  c  o  m
 * @param cmykProfile
 * @return The BufferedImage obj
 * @throws IOException
 */
private static BufferedImage convertCmykToRgb(Raster cmykRaster, ICC_Profile cmykProfile) throws IOException {
    if (cmykProfile == null) {
        cmykProfile = ICC_Profile.getInstance(
                CustomExtraImgReader.class.getResourceAsStream(Consts.RESOURCEPATH + Consts.GENERICICCFILE));
    }
    if (cmykProfile.getProfileClass() != ICC_Profile.CLASS_DISPLAY) {
        byte[] profileData = cmykProfile.getData();
        if (profileData[ICC_Profile.icHdrRenderingIntent] == ICC_Profile.icPerceptual) {
            intToBigEndian(ICC_Profile.icSigDisplayClass, profileData, ICC_Profile.icHdrDeviceClass);
            cmykProfile = ICC_Profile.getInstance(profileData);
        }
    }

    ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile);
    BufferedImage rgbImage = new BufferedImage(cmykRaster.getWidth(), cmykRaster.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();
    ColorSpace rgbCS = rgbImage.getColorModel().getColorSpace();
    ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null);
    cmykToRgb.filter(cmykRaster, rgbRaster);
    return rgbImage;
}

From source file:org.sejda.sambox.pdmodel.graphics.color.PDICCBased.java

/**
 * Load the ICC profile, or init alternateColorSpace color space.
 *//*from  w ww  . ja v a 2s.c  om*/
private void loadICCProfile() throws IOException {
    InputStream input = null;
    try {
        input = this.stream.createInputStream();

        // if the embedded profile is sRGB then we can use Java's built-in profile, which
        // results in a large performance gain as it's our native color space, see PDFBOX-2587
        ICC_Profile profile;
        synchronized (LOG) {
            profile = ICC_Profile.getInstance(input);
        }
        if (is_sRGB(profile)) {
            awtColorSpace = (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_sRGB);
            iccProfile = awtColorSpace.getProfile();
        } else {
            awtColorSpace = new ICC_ColorSpace(profile);
            iccProfile = profile;
        }

        // set initial colour
        float[] initial = new float[getNumberOfComponents()];
        for (int c = 0; c < getNumberOfComponents(); c++) {
            initial[c] = Math.max(0, getRangeForComponent(c).getMin());
        }
        initialColor = new PDColor(initial, this);

        // create a color in order to trigger a ProfileDataException
        // or CMMException due to invalid profiles, see PDFBOX-1295 and PDFBOX-1740
        new Color(awtColorSpace, new float[getNumberOfComponents()], 1f);
    } catch (RuntimeException e) {
        if (e instanceof ProfileDataException || e instanceof CMMException
                || e instanceof IllegalArgumentException) {
            // fall back to alternateColorSpace color space
            awtColorSpace = null;
            alternateColorSpace = getAlternateColorSpace();
            LOG.error("Can't read embedded ICC profile (" + e.getLocalizedMessage()
                    + "), using alternate color space: " + alternateColorSpace.getName());
            initialColor = alternateColorSpace.getInitialColor();
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:paintbasico2d.VentanaPrincipal.java

private void EscalaGrisesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EscalaGrisesActionPerformed
    // TODO add your handling code here:
    VentanaInterna vi = (VentanaInterna) escritorio.getSelectedFrame();
    if (vi != null) {
        vi.getLienzo().setImage(vi.getLienzo().getImage());
        if (vi.getLienzo().getImage() != null) {
            ICC_Profile icc = ICC_Profile.getInstance(ColorSpace.CS_GRAY);
            ColorSpace cs = new ICC_ColorSpace(icc);
            ColorConvertOp conver = new ColorConvertOp(cs, null);
            BufferedImage imgdest = conver.filter(vi.getLienzo().getImage(), null);
            vi.getLienzo().setImage(imgdest);
        }/*ww  w . j a v  a2s.c o  m*/
    }
    repaint();
}