Example usage for java.awt.color ICC_Profile getInstance

List of usage examples for java.awt.color ICC_Profile getInstance

Introduction

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

Prototype

public static ICC_Profile getInstance(InputStream s) throws IOException 

Source Link

Document

Constructs an ICC_Profile corresponding to the data in an InputStream .

Usage

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

/**
 * Put PDF-A-Infos to the document./*from w  w w . ja v  a2s  . c  o m*/
 * @param writer the pdf-writer.
 * @throws IOException IOException.
 */
private void addPdfAInfosToDictonary(PdfWriter writer) throws IOException {
    PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT);
    outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
    outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
    outi.put(PdfName.S, PdfName.GTS_PDFA1);

    ICC_Profile icc = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
    PdfICCBased ib = new PdfICCBased(icc);
    ib.remove(PdfName.ALTERNATE);
    outi.put(PdfName.DESTOUTPUTPROFILE, writer.addToBody(ib).getIndirectReference());
    writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi));
}

From source file:net.sf.jasperreports.engine.export.JRPdfExporter.java

/**
 *
 *//*from w  ww .  ja  va2 s.  com*/
protected void exportReportToStream(OutputStream os) throws JRException {
    //ByteArrayOutputStream baos = new ByteArrayOutputStream();

    PdfExporterConfiguration configuration = getCurrentConfiguration();

    pageFormat = jasperPrint.getPageFormat(0);

    document = new Document(new Rectangle(pageFormat.getPageWidth(), pageFormat.getPageHeight()));

    imageTesterDocument = new Document(new Rectangle(10, //jasperPrint.getPageWidth(),
            10 //jasperPrint.getPageHeight()
    ));

    boolean closeDocuments = true;
    try {
        pdfWriter = PdfWriter.getInstance(document, os);
        pdfWriter.setCloseStream(false);

        tagHelper.setPdfWriter(pdfWriter);

        PdfVersionEnum pdfVersion = configuration.getPdfVersion();
        if (pdfVersion != null) {
            pdfWriter.setPdfVersion(pdfVersion.getName().charAt(0));
        }

        if (minimalVersion != null) {
            pdfWriter.setAtLeastPdfVersion(minimalVersion.getName().charAt(0));
        }

        if (configuration.isCompressed()) {
            pdfWriter.setFullCompression();
        }
        if (configuration.isEncrypted()) {
            int perms = configuration.isOverrideHints() == null || configuration.isOverrideHints()
                    ? (configuration.getPermissions() != null ? (Integer) configuration.getPermissions()
                            : permissions)
                    : (permissions != 0 ? permissions
                            : (configuration.getPermissions() != null ? (Integer) configuration.getPermissions()
                                    : 0));

            pdfWriter.setEncryption(PdfWriter.getISOBytes(configuration.getUserPassword()),
                    PdfWriter.getISOBytes(configuration.getOwnerPassword()), perms,
                    configuration.is128BitKey() ? PdfWriter.STANDARD_ENCRYPTION_128
                            : PdfWriter.STANDARD_ENCRYPTION_40);
        }

        PdfPrintScalingEnum printScaling = configuration.getPrintScaling();
        if (PdfPrintScalingEnum.DEFAULT == printScaling) {
            pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.APPDEFAULT);
        } else if (PdfPrintScalingEnum.NONE == printScaling) {
            pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
        }

        boolean justifiedLetterSpacing = propertiesUtil.getBooleanProperty(jasperPrint,
                PdfExporterConfiguration.PROPERTY_JUSTIFIED_LETTER_SPACING, false);
        if (!justifiedLetterSpacing) {
            pdfWriter.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
        }

        // Add meta-data parameters to generated PDF document
        // mtclough@users.sourceforge.net 2005-12-05
        String title = configuration.getMetadataTitle();
        if (title != null) {
            document.addTitle(title);
            if (configuration.isDisplayMetadataTitle()) {
                pdfWriter.addViewerPreference(PdfName.DISPLAYDOCTITLE, new PdfBoolean(true));
            }
        }
        String author = configuration.getMetadataAuthor();
        if (author != null) {
            document.addAuthor(author);
        }
        String subject = configuration.getMetadataSubject();
        if (subject != null) {
            document.addSubject(subject);
        }
        String keywords = configuration.getMetadataKeywords();
        if (keywords != null) {
            document.addKeywords(keywords);
        }
        String creator = configuration.getMetadataCreator();
        if (creator == null) {
            creator = "JasperReports Library version "
                    + Package.getPackage("net.sf.jasperreports.engine").getImplementationVersion();
        }
        document.addCreator(creator);

        //accessibility check: tab order follows the structure of the document
        pdfWriter.setTabs(PdfName.S);

        //accessibility check: setting the document primary language
        String language = configuration.getTagLanguage();
        if (language != null) {
            pdfWriter.getExtraCatalog().put(PdfName.LANG, new PdfString(language));
        }

        // BEGIN: PDF/A support
        PdfaConformanceEnum pdfaConformance = configuration.getPdfaConformance();
        boolean gotPdfa = false;
        if (PdfaConformanceEnum.PDFA_1A == pdfaConformance) {
            pdfWriter.setPDFXConformance(PdfWriter.PDFA1A);
            gotPdfa = true;
        } else if (PdfaConformanceEnum.PDFA_1B == pdfaConformance) {
            pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);
            gotPdfa = true;
        }

        if (gotPdfa) {
            if (PdfXmpCreator.supported()) {
                byte[] metadata = PdfXmpCreator.createXmpMetadata(pdfWriter);
                pdfWriter.setXmpMetadata(metadata);
            } else {
                if ((title != null || subject != null || keywords != null) && log.isWarnEnabled()) {
                    // iText 2.1.7 does not properly write localized properties and keywords
                    log.warn("XMP metadata might be non conforming, include the Adobe XMP library to correct");
                }

                pdfWriter.createXmpMetadata();
            }
        } else {
            pdfWriter.setRgbTransparencyBlending(true);
        }
        // END: PDF/A support

        document.open();
        // BEGIN: PDF/A support
        if (gotPdfa) {
            String iccProfilePath = configuration.getIccProfilePath();
            if (iccProfilePath != null) {
                PdfDictionary pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT);
                pdfDictionary.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
                pdfDictionary.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
                pdfDictionary.put(PdfName.S, PdfName.GTS_PDFA1);
                InputStream iccIs = RepositoryUtil.getInstance(jasperReportsContext)
                        .getInputStreamFromLocation(iccProfilePath);//FIXME use getRepository?
                PdfICCBased pdfICCBased = new PdfICCBased(ICC_Profile.getInstance(iccIs));
                pdfICCBased.remove(PdfName.ALTERNATE);
                pdfDictionary.put(PdfName.DESTOUTPUTPROFILE,
                        pdfWriter.addToBody(pdfICCBased).getIndirectReference());

                pdfWriter.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary));
            } else {
                throw new JRPdfaIccProfileNotFoundException();
            }
        }
        // END: PDF/A support

        String pdfJavaScript = configuration.getPdfJavaScript();
        if (pdfJavaScript != null) {
            pdfWriter.addJavaScript(pdfJavaScript);
        }

        pdfContentByte = pdfWriter.getDirectContent();

        tagHelper.init(pdfContentByte);

        PdfWriter imageTesterPdfWriter = PdfWriter.getInstance(imageTesterDocument, new NullOutputStream() // discard the output
        );
        imageTesterDocument.open();
        imageTesterDocument.newPage();
        imageTesterPdfContentByte = imageTesterPdfWriter.getDirectContent();
        imageTesterPdfContentByte.setLiteral("\n");

        List<ExporterInputItem> items = exporterInput.getItems();

        initBookmarks(items);

        boolean isCreatingBatchModeBookmarks = configuration.isCreatingBatchModeBookmarks();

        for (reportIndex = 0; reportIndex < items.size(); reportIndex++) {
            ExporterInputItem item = items.get(reportIndex);

            setCurrentExporterInputItem(item);

            pageFormat = jasperPrint.getPageFormat(0);

            setPageSize(null);

            List<JRPrintPage> pages = jasperPrint.getPages();
            if (pages != null && pages.size() > 0) {
                if (items.size() > 1) {
                    document.newPage();

                    if (isCreatingBatchModeBookmarks) {
                        //add a new level to our outline for this report
                        addBookmark(0, jasperPrint.getName(), 0, 0);
                    }
                }

                PdfReportConfiguration lcItemConfiguration = getCurrentItemConfiguration();

                boolean sizePageToContent = lcItemConfiguration.isSizePageToContent();

                PrintPageFormat oldPageFormat = null;

                PageRange pageRange = getPageRange();
                int startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0
                        : pageRange.getStartPageIndex();
                int endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null)
                        ? (pages.size() - 1)
                        : pageRange.getEndPageIndex();

                for (int pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                    if (Thread.interrupted()) {
                        throw new ExportInterruptedException();
                    }

                    JRPrintPage page = pages.get(pageIndex);

                    pageFormat = jasperPrint.getPageFormat(pageIndex);

                    if (sizePageToContent || oldPageFormat != pageFormat) {
                        setPageSize(sizePageToContent ? page : null);
                    }

                    document.newPage();

                    pdfContentByte = pdfWriter.getDirectContent();

                    pdfContentByte.setLineCap(2);//PdfContentByte.LINE_CAP_PROJECTING_SQUARE since iText 1.02b

                    writePageAnchor(pageIndex);

                    crtDocumentPageNumber++;

                    /*   */
                    exportPage(page);

                    oldPageFormat = pageFormat;
                }
            } else {
                document.newPage();
                pdfContentByte = pdfWriter.getDirectContent();
                pdfContentByte.setLiteral("\n");
            }
        }

        closeDocuments = false;
        document.close();
        imageTesterDocument.close();
    } catch (DocumentException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_DOCUMENT_ERROR, new Object[] { jasperPrint.getName() }, e);
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_REPORT_GENERATION_ERROR,
                new Object[] { jasperPrint.getName() }, e);
    } finally {
        if (closeDocuments) //only on exception
        {
            try {
                document.close();
            } catch (Exception e) {
                // ignore, let the original exception propagate
            }

            try {
                imageTesterDocument.close();
            } catch (Exception e) {
                // ignore, let the original exception propagate
            }
        }
    }

    //return os.toByteArray();
}

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 .  ja  v a  2  s . c om
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

private ICC_Profile tryToExctractICCProfileFromPNGMetadataNode(Element pngNode) {
    ICC_Profile iccProf = null;/*from   w  w w . j a  v a2 s  . com*/
    Element iccpNode = ImageIOUtil.getChild(pngNode, "iCCP");
    if (iccpNode instanceof IIOMetadataNode) {
        IIOMetadataNode imn = (IIOMetadataNode) iccpNode;
        byte[] prof = (byte[]) imn.getUserObject();
        String comp = imn.getAttribute("compressionMethod");
        if ("deflate".equalsIgnoreCase(comp)) {
            Inflater decompresser = new Inflater();
            decompresser.setInput(prof);
            byte[] result = new byte[100];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean failed = false;
            while (!decompresser.finished() && !failed) {
                try {
                    int resultLength = decompresser.inflate(result);
                    bos.write(result, 0, resultLength);
                    if (resultLength == 0) {
                        // this means more data or an external dictionary is
                        // needed. Both of which are not available, so we
                        // fail.
                        log.debug("Failed to deflate ICC Profile");
                        failed = true;
                    }
                } catch (DataFormatException e) {
                    log.debug("Failed to deflate ICC Profile", e);
                    failed = true;
                }
            }
            decompresser.end();
            try {
                iccProf = ICC_Profile.getInstance(bos.toByteArray());
            } catch (IllegalArgumentException e) {
                log.debug("Failed to interpret embedded ICC Profile", e);
                iccProf = null;
            }
        }
    }
    return iccProf;
}

From source file:org.apache.xmlgraphics.image.loader.impl.ImageLoaderRawJPEG.java

private ICC_Profile buildICCProfile(ImageInfo info, ColorSpace colorSpace, ByteArrayOutputStream iccStream)
        throws IOException, ImageException {
    if (iccStream != null && iccStream.size() > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Effective ICC profile size: " + iccStream.size());
        }/*w  w  w .  j a  v  a 2  s. c o m*/
        final int alignment = 4;
        int padding = (alignment - (iccStream.size() % alignment)) % alignment;
        if (padding != 0) {
            try {
                iccStream.write(new byte[padding]);
            } catch (IOException ioe) {
                throw new IOException("Error while aligning ICC stream: " + ioe.getMessage());
            }
        }

        ICC_Profile iccProfile = null;
        try {
            iccProfile = ICC_Profile.getInstance(iccStream.toByteArray());
            if (log.isDebugEnabled()) {
                log.debug("JPEG has an ICC profile: " + iccProfile.toString());
            }
        } catch (IllegalArgumentException iae) {
            log.warn("An ICC profile is present in the JPEG file but it is invalid (" + iae.getMessage()
                    + "). The color profile will be ignored. (" + info.getOriginalURI() + ")");
            return null;
        }
        if (iccProfile.getNumComponents() != colorSpace.getNumComponents()) {
            log.warn("The number of components of the ICC profile (" + iccProfile.getNumComponents()
                    + ") doesn't match the image (" + colorSpace.getNumComponents()
                    + "). Ignoring the ICC color profile.");
            return null;
        } else {
            return iccProfile;
        }
    } else {
        return null; //no ICC profile available
    }
}

From source file:org.apache.xmlgraphics.java2d.color.profile.NamedColorProfileParserTest.java

public void testParser() throws Exception {
    final InputStream in = getClass().getResourceAsStream(NCP_EXAMPLE_FILE);
    assertNotNull(NCP_EXAMPLE_FILE + " is missing!", in);
    ICC_Profile iccProfile;//from www  .ja va  2s  .co  m
    try {
        iccProfile = ICC_Profile.getInstance(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    final NamedColorProfileParser parser = new NamedColorProfileParser();
    final NamedColorProfile ncp = parser.parseProfile(iccProfile);
    assertEquals("Named Color Profile Example", ncp.getProfileName());
    assertEquals("The Apache Software Foundation", ncp.getCopyright());
    assertEquals(RenderingIntent.PERCEPTUAL, ncp.getRenderingIntent());
    final NamedColorSpace[] namedColors = ncp.getNamedColors();
    assertEquals(2, namedColors.length);
    NamedColorSpace ncs;
    ncs = namedColors[0];
    assertEquals("Postgelb", ncs.getColorName());
    final float[] xyz = ncs.getXYZ();
    assertEquals(0.6763079f, xyz[0], 0.01f);
    assertEquals(0.6263507f, xyz[1], 0.01f);
    assertEquals(0.04217565f, xyz[2], 0.01f);

    ncs = namedColors[1];
    assertEquals("MyRed", ncs.getColorName());
}

From source file:org.gmdev.pdftrick.utils.CustomExtraImgReader.java

/**
 * Convert image from Cmyk to Rgb profile
 * @param cmykRaster/*  www  . j  a v a 2  s.com*/
 * @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.goobi.presentation.contentservlet.controller.GetMetsPdfAction.java

/************************************************************************************
 * set some properties depending on config file
 * //from   w ww  . j a va 2 s . c  o  m
 * @param request {@link HttpServletRequest} of ServletRequest
 * @param config instance of ContentServerConfiguration
 * @param pdfmanager {@link PDFManager} where to set the properties
 * @throws IOException
 ************************************************************************************/
protected void setPdfManagerDefaults(HttpServletRequest request, ContentServerConfiguration config,
        PDFManager pdfmanager) throws IOException {

    pdfmanager.setAlwaysUseRenderedImage(config.getPdfDefaultAlwaysUseRenderedImage());
    pdfmanager.setAlwaysCompressToJPEG(config.getPdfDefaultAlwaysCompressToJPEG());

    if (config.getWatermarkUse()) {
        try {
            File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
            if (request.getParameterMap().containsKey("watermarkText")) {
                myWatermark = new Watermark(watermarkfile, request.getParameter("watermarkText"));
            } else {
                myWatermark = new Watermark(watermarkfile);
            }
        } catch (WatermarkException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /*
     * -------------------------------- set ICC profile --------------------------------
     */

    File iccfile = new File(Util.getBaseFolderAsFile(), "sRGB.icc");
    ICC_Profile icc = null;

    if (!iccfile.exists()) {
        InputStream is = GetMetsPdfAction.class.getResourceAsStream("sRGB.icc");
        if (is != null) {
            icc = ICC_Profile.getInstance(is);
        }
    } else {
        icc = ICC_Profile.getInstance(iccfile.getAbsolutePath());
    }

    if (icc != null) {
        pdfmanager.setIccprofile(icc);
    } else {
        LOGGER.error("No ICC profile given!");
    }

    /*
     * -------------------------------- check if pdf should be written as pdf/A, if configured in request parameter, else take it from config file
     * --------------------------------
     */
    boolean pdfa = Boolean.parseBoolean(getParameterFromRequestOrConfig("writeAsPdfA", request));
    pdfmanager.setPdfa(pdfa);
}

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

/**
 * Load the ICC profile, or init alternateColorSpace color space.
 *//*from  ww  w. j ava2 s . c o  m*/
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);
        }/*from w w w  . java2  s . com*/
    }
    repaint();
}