Java Examples for java.awt.color.ICC_Profile

The following java examples will help you to understand the usage of java.awt.color.ICC_Profile. These source code samples are taken from different open source projects.

Example 1
Project: openjdk-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List<? extends BufferedImage> thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator<MarkerSegment> iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 2
Project: PSD-master  File: TIFFImageReader.java View source code
@Override
public ImageTypeSpecifier getRawImageType(int imageIndex) throws IOException {
    readIFD(imageIndex);
    int sampleFormat = getSampleFormat();
    int planarConfiguration = getValueAsIntWithDefault(TIFF.TAG_PLANAR_CONFIGURATION, TIFFBaseline.PLANARCONFIG_CHUNKY);
    int interpretation = getPhotometricInterpretationWithFallback();
    int samplesPerPixel = getValueAsIntWithDefault(TIFF.TAG_SAMPLES_PER_PIXEL, 1);
    int bitsPerSample = getBitsPerSample();
    int dataType = getDataType(sampleFormat, bitsPerSample);
    int opaqueSamplesPerPixel = getOpaqueSamplesPerPixel(interpretation);
    // Spec says ExtraSamples are mandatory of extra samples, however known encoders
    // (ie. SeaShore) writes ARGB TIFFs without ExtraSamples.
    long[] extraSamples = getValueAsLongArray(TIFF.TAG_EXTRA_SAMPLES, "ExtraSamples", false);
    if (extraSamples == null && samplesPerPixel > opaqueSamplesPerPixel) {
        // TODO: Log warning!
        // First extra is alpha, rest is "unspecified"
        extraSamples = new long[samplesPerPixel - opaqueSamplesPerPixel];
        extraSamples[0] = TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA;
    }
    // Determine alpha
    boolean hasAlpha = extraSamples != null;
    boolean isAlphaPremultiplied = hasAlpha && extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA;
    int significantSamples = opaqueSamplesPerPixel + (hasAlpha ? 1 : 0);
    // Read embedded cs
    ICC_Profile profile = getICCProfile();
    ColorSpace cs;
    switch(interpretation) {
        // TIFF 6.0 baseline
        case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
        // NOTE: We handle this by inverting the values when reading, as Java has no ColorModel that easily supports this.
        case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
            // Gray scale or B/W
            switch(significantSamples) {
                case 1:
                    // (Chunky or planar makes no difference for a single channel).
                    if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
                        processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
                        profile = null;
                    }
                    cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
                    if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 || bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
                        return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType);
                    } else if (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4) {
                        // Use packed format for 1/2/4 bits
                        return ImageTypeSpecifiers.createPackedGrayscale(cs, bitsPerSample, dataType);
                    } else if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0 }, dataType, false, false);
                    } else if (bitsPerSample % 2 == 0) {
                        ColorModel colorModel = new ComponentColorModel(cs, new int[] { bitsPerSample }, false, false, Transparency.OPAQUE, dataType);
                        return new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1));
                    }
                    throw new IIOException(String.format("Unsupported BitsPerSample for Bi-level/Gray TIFF (expected 1, 2, 4, 8, 16 or 32): %d", bitsPerSample));
                case 2:
                    // * Chunky (interleaved) or planar (banded) data
                    if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
                        processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
                        profile = null;
                    }
                    cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
                    if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    } else if (/*bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 ||*/
                    bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        // TODO: For 1/2/4 bit planar, we might need to fix while reading... Look at IFFImageReader?
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    }
                    throw new IIOException(String.format("Unsupported BitsPerSample for Gray + Alpha TIFF (expected 8, 16 or 32): %d", bitsPerSample));
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Bi-level/Gray TIFF (expected 1/1, 1/2, 1/4, 1/8, 1/16 or 1/32, or 2/8, 2/16 or 2/32): %d/%d", samplesPerPixel, bitsPerSample));
            }
        case TIFFExtension.PHOTOMETRIC_YCBCR:
        // TODO: Sanity check that we have SamplesPerPixel == 3, BitsPerSample == [8,8,8] (or [16,16,16]) and Compression == 1 (none), 5 (LZW), or 6 (JPEG)
        case TIFFBaseline.PHOTOMETRIC_RGB:
            // RGB
            if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_RGB) {
                processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (RGB/type 5). Ignoring profile.", profile.getColorSpaceType()));
                profile = null;
            }
            cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_sRGB) : ColorSpaces.createColorSpace(profile);
            switch(significantSamples) {
                case 3:
                    if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                // "TYPE_3BYTE_RGB" if cs.isCS_sRGB()
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2 }, dataType, false, false);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, dataType, false, false);
                        }
                    } else if (bitsPerSample > 8 && bitsPerSample % 2 == 0) {
                        // TODO: Support variable bits/sample?
                        ColorModel colorModel = new ComponentColorModel(cs, new int[] { bitsPerSample, bitsPerSample, bitsPerSample }, false, false, Transparency.OPAQUE, dataType);
                        SampleModel sampleModel = planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY ? colorModel.createCompatibleSampleModel(1, 1) : new BandedSampleModel(dataType, 1, 1, 3, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 });
                        return new ImageTypeSpecifier(colorModel, sampleModel);
                    }
                case 4:
                    if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                // "TYPE_4BYTE_RGBA" if cs.isCS_sRGB()
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    } else if (significantSamples == 4 && bitsPerSample == 4) {
                        return ImageTypeSpecifiers.createPacked(cs, 0xF000, 0xF00, 0xF0, 0xF, DataBuffer.TYPE_USHORT, isAlphaPremultiplied);
                    }
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for RGB TIFF (expected 3/8, 4/8, 3/16 or 4/16): %d/%d", samplesPerPixel, bitsPerSample));
            }
        case TIFFBaseline.PHOTOMETRIC_PALETTE:
            // Palette
            if (samplesPerPixel != 1 && !(samplesPerPixel == 2 && extraSamples != null && extraSamples.length == 1)) {
                throw new IIOException("Bad SamplesPerPixel value for Palette TIFF (expected 1): " + samplesPerPixel);
            } else if (bitsPerSample <= 0 || bitsPerSample > 16) {
                throw new IIOException("Bad BitsPerSample value for Palette TIFF (expected <= 16): " + bitsPerSample);
            }
            // NOTE: If ExtraSamples is used, PlanarConfiguration must be taken into account also for pixel data
            Entry colorMap = currentIFD.getEntryById(TIFF.TAG_COLOR_MAP);
            if (colorMap == null) {
                throw new IIOException("Missing ColorMap for Palette TIFF");
            }
            IndexColorModel icm = createIndexColorModel(bitsPerSample, dataType, (int[]) colorMap.getValue());
            if (extraSamples != null && extraSamples.length > 0 && (extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA || extraSamples[0] == TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA)) {
                return ImageTypeSpecifiers.createDiscreteAlphaIndexedFromIndexColorModel(icm);
            }
            return ImageTypeSpecifiers.createFromIndexColorModel(icm);
        case TIFFExtension.PHOTOMETRIC_SEPARATED:
            // Separated (CMYK etc)
            // Consult the 332/InkSet (1=CMYK, 2=Not CMYK; see InkNames), 334/NumberOfInks (def=4) and optionally 333/InkNames
            // If "Not CMYK" we'll need an ICC profile to be able to display (in a useful way), readAsRaster should still work.
            int inkSet = getValueAsIntWithDefault(TIFF.TAG_INK_SET, TIFFExtension.INKSET_CMYK);
            int numberOfInks = getValueAsIntWithDefault(TIFF.TAG_NUMBER_OF_INKS, 4);
            // Profile must be CMYK, OR color component must match NumberOfInks
            if (inkSet != TIFFExtension.INKSET_CMYK && (profile == null || profile.getNumComponents() != numberOfInks)) {
                throw new IIOException(String.format("Embedded ICC color profile for Photometric Separated is missing or is incompatible with image data: %s != NumberOfInks (%s).", profile != null ? profile.getNumComponents() : "null", numberOfInks));
            }
            if (profile != null && inkSet == TIFFExtension.INKSET_CMYK && profile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
                processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (CMYK/type 9). Ignoring profile.", profile.getColorSpaceType()));
                profile = null;
            }
            cs = profile == null ? ColorSpaces.getColorSpace(ColorSpaces.CS_GENERIC_CMYK) : ColorSpaces.createColorSpace(profile);
            switch(significantSamples) {
                case 4:
                    if (bitsPerSample == 8 || bitsPerSample == 16) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3 }, dataType, false, false);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, dataType, false, false);
                        }
                    }
                case 5:
                    if (bitsPerSample == 8 || bitsPerSample == 16) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3, 4 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    }
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Separated TIFF (expected 4/8, 4/16, 5/8 or 5/16): %d/%s", samplesPerPixel, bitsPerSample));
            }
        case TIFFExtension.PHOTOMETRIC_CIELAB:
        case TIFFExtension.PHOTOMETRIC_ICCLAB:
        case TIFFExtension.PHOTOMETRIC_ITULAB:
            // TODO: Would probably be more correct to handle using a CIELabColorSpace for RAW type?
            // L*a*b* color. Handled using conversion to sRGB
            cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
            switch(planarConfiguration) {
                case TIFFBaseline.PLANARCONFIG_CHUNKY:
                    return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2 }, dataType, false, false);
                case TIFFExtension.PLANARCONFIG_PLANAR:
                //return ImageTypeSpecifiers.createBanded(cs, new int[] {0, 1, 2}, new int[] {0, 0, 0}, dataType, false, false);
                default:
                    throw new IIOException(String.format("Unsupported PlanarConfiguration for Lab color TIFF (expected 1): %d", planarConfiguration));
            }
        case TIFFBaseline.PHOTOMETRIC_MASK:
        // TODO: Treat as grey?
        case TIFFCustom.PHOTOMETRIC_LOGL:
        case TIFFCustom.PHOTOMETRIC_LOGLUV:
        // Log
        case TIFFCustom.PHOTOMETRIC_CFA:
        case TIFFCustom.PHOTOMETRIC_LINEAR_RAW:
            // RAW (DNG)
            throw new IIOException("Unsupported TIFF PhotometricInterpretation value: " + interpretation);
        default:
            throw new IIOException("Unknown TIFF PhotometricInterpretation value: " + interpretation);
    }
}
Example 3
Project: TwelveMonkeys-master  File: TIFFImageReader.java View source code
@Override
public ImageTypeSpecifier getRawImageType(int imageIndex) throws IOException {
    readIFD(imageIndex);
    int sampleFormat = getSampleFormat();
    int planarConfiguration = getValueAsIntWithDefault(TIFF.TAG_PLANAR_CONFIGURATION, TIFFBaseline.PLANARCONFIG_CHUNKY);
    int interpretation = getPhotometricInterpretationWithFallback();
    int samplesPerPixel = getValueAsIntWithDefault(TIFF.TAG_SAMPLES_PER_PIXEL, 1);
    int bitsPerSample = getBitsPerSample();
    int dataType = getDataType(sampleFormat, bitsPerSample);
    int opaqueSamplesPerPixel = getOpaqueSamplesPerPixel(interpretation);
    // Spec says ExtraSamples are mandatory of extra samples, however known encoders
    // (ie. SeaShore) writes ARGB TIFFs without ExtraSamples.
    long[] extraSamples = getValueAsLongArray(TIFF.TAG_EXTRA_SAMPLES, "ExtraSamples", false);
    if (extraSamples == null && samplesPerPixel > opaqueSamplesPerPixel) {
        // TODO: Log warning!
        // First extra is alpha, rest is "unspecified"
        extraSamples = new long[samplesPerPixel - opaqueSamplesPerPixel];
        extraSamples[0] = TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA;
    }
    // Determine alpha
    boolean hasAlpha = extraSamples != null;
    boolean isAlphaPremultiplied = hasAlpha && extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA;
    int significantSamples = opaqueSamplesPerPixel + (hasAlpha ? 1 : 0);
    // Read embedded cs
    ICC_Profile profile = getICCProfile();
    ColorSpace cs;
    switch(interpretation) {
        // TIFF 6.0 baseline
        case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
        // NOTE: We handle this by inverting the values when reading, as Java has no ColorModel that easily supports this.
        case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
            // Gray scale or B/W
            switch(significantSamples) {
                case 1:
                    // (Chunky or planar makes no difference for a single channel).
                    if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
                        processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
                        profile = null;
                    }
                    cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
                    if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 || bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
                        return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType);
                    } else if (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4) {
                        // Use packed format for 1/2/4 bits
                        return ImageTypeSpecifiers.createPackedGrayscale(cs, bitsPerSample, dataType);
                    } else if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0 }, dataType, false, false);
                    } else if (bitsPerSample % 2 == 0) {
                        ColorModel colorModel = new ComponentColorModel(cs, new int[] { bitsPerSample }, false, false, Transparency.OPAQUE, dataType);
                        return new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1));
                    }
                    throw new IIOException(String.format("Unsupported BitsPerSample for Bi-level/Gray TIFF (expected 1, 2, 4, 8, 16 or 32): %d", bitsPerSample));
                case 2:
                    // * Chunky (interleaved) or planar (banded) data
                    if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
                        processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
                        profile = null;
                    }
                    cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
                    if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    } else if (/*bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 ||*/
                    bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        // TODO: For 1/2/4 bit planar, we might need to fix while reading... Look at IFFImageReader?
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    }
                    throw new IIOException(String.format("Unsupported BitsPerSample for Gray + Alpha TIFF (expected 8, 16 or 32): %d", bitsPerSample));
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Bi-level/Gray TIFF (expected 1/1, 1/2, 1/4, 1/8, 1/16 or 1/32, or 2/8, 2/16 or 2/32): %d/%d", samplesPerPixel, bitsPerSample));
            }
        case TIFFExtension.PHOTOMETRIC_YCBCR:
        // TODO: Sanity check that we have SamplesPerPixel == 3, BitsPerSample == [8,8,8] (or [16,16,16]) and Compression == 1 (none), 5 (LZW), or 6 (JPEG)
        case TIFFBaseline.PHOTOMETRIC_RGB:
            // RGB
            if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_RGB) {
                processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (RGB/type 5). Ignoring profile.", profile.getColorSpaceType()));
                profile = null;
            }
            cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_sRGB) : ColorSpaces.createColorSpace(profile);
            switch(significantSamples) {
                case 3:
                    if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                // "TYPE_3BYTE_RGB" if cs.isCS_sRGB()
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2 }, dataType, false, false);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, dataType, false, false);
                        }
                    } else if (bitsPerSample > 8 && bitsPerSample % 2 == 0) {
                        // TODO: Support variable bits/sample?
                        ColorModel colorModel = new ComponentColorModel(cs, new int[] { bitsPerSample, bitsPerSample, bitsPerSample }, false, false, Transparency.OPAQUE, dataType);
                        SampleModel sampleModel = planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY ? colorModel.createCompatibleSampleModel(1, 1) : new BandedSampleModel(dataType, 1, 1, 3, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 });
                        return new ImageTypeSpecifier(colorModel, sampleModel);
                    }
                case 4:
                    if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                // "TYPE_4BYTE_RGBA" if cs.isCS_sRGB()
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    } else if (significantSamples == 4 && bitsPerSample == 4) {
                        return ImageTypeSpecifiers.createPacked(cs, 0xF000, 0xF00, 0xF0, 0xF, DataBuffer.TYPE_USHORT, isAlphaPremultiplied);
                    }
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for RGB TIFF (expected 3/8, 4/8, 3/16 or 4/16): %d/%d", samplesPerPixel, bitsPerSample));
            }
        case TIFFBaseline.PHOTOMETRIC_PALETTE:
            // Palette
            if (samplesPerPixel != 1 && !(samplesPerPixel == 2 && extraSamples != null && extraSamples.length == 1)) {
                throw new IIOException("Bad SamplesPerPixel value for Palette TIFF (expected 1): " + samplesPerPixel);
            } else if (bitsPerSample <= 0 || bitsPerSample > 16) {
                throw new IIOException("Bad BitsPerSample value for Palette TIFF (expected <= 16): " + bitsPerSample);
            }
            // NOTE: If ExtraSamples is used, PlanarConfiguration must be taken into account also for pixel data
            Entry colorMap = currentIFD.getEntryById(TIFF.TAG_COLOR_MAP);
            if (colorMap == null) {
                throw new IIOException("Missing ColorMap for Palette TIFF");
            }
            IndexColorModel icm = createIndexColorModel(bitsPerSample, dataType, (int[]) colorMap.getValue());
            if (extraSamples != null && extraSamples.length > 0 && (extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA || extraSamples[0] == TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA)) {
                return ImageTypeSpecifiers.createDiscreteAlphaIndexedFromIndexColorModel(icm);
            }
            return ImageTypeSpecifiers.createFromIndexColorModel(icm);
        case TIFFExtension.PHOTOMETRIC_SEPARATED:
            // Separated (CMYK etc)
            // Consult the 332/InkSet (1=CMYK, 2=Not CMYK; see InkNames), 334/NumberOfInks (def=4) and optionally 333/InkNames
            // If "Not CMYK" we'll need an ICC profile to be able to display (in a useful way), readAsRaster should still work.
            int inkSet = getValueAsIntWithDefault(TIFF.TAG_INK_SET, TIFFExtension.INKSET_CMYK);
            int numberOfInks = getValueAsIntWithDefault(TIFF.TAG_NUMBER_OF_INKS, 4);
            // Profile must be CMYK, OR color component must match NumberOfInks
            if (inkSet != TIFFExtension.INKSET_CMYK && (profile == null || profile.getNumComponents() != numberOfInks)) {
                throw new IIOException(String.format("Embedded ICC color profile for Photometric Separated is missing or is incompatible with image data: %s != NumberOfInks (%s).", profile != null ? profile.getNumComponents() : "null", numberOfInks));
            }
            if (profile != null && inkSet == TIFFExtension.INKSET_CMYK && profile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
                processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (CMYK/type 9). Ignoring profile.", profile.getColorSpaceType()));
                profile = null;
            }
            cs = profile == null ? ColorSpaces.getColorSpace(ColorSpaces.CS_GENERIC_CMYK) : ColorSpaces.createColorSpace(profile);
            switch(significantSamples) {
                case 4:
                    if (bitsPerSample == 8 || bitsPerSample == 16) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3 }, dataType, false, false);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, dataType, false, false);
                        }
                    }
                case 5:
                    if (bitsPerSample == 8 || bitsPerSample == 16) {
                        switch(planarConfiguration) {
                            case TIFFBaseline.PLANARCONFIG_CHUNKY:
                                return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2, 3, 4 }, dataType, true, isAlphaPremultiplied);
                            case TIFFExtension.PLANARCONFIG_PLANAR:
                                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, dataType, true, isAlphaPremultiplied);
                        }
                    }
                default:
                    throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Separated TIFF (expected 4/8, 4/16, 5/8 or 5/16): %d/%s", samplesPerPixel, bitsPerSample));
            }
        case TIFFExtension.PHOTOMETRIC_CIELAB:
        case TIFFExtension.PHOTOMETRIC_ICCLAB:
        case TIFFExtension.PHOTOMETRIC_ITULAB:
            // TODO: Would probably be more correct to handle using a CIELabColorSpace for RAW type?
            // L*a*b* color. Handled using conversion to sRGB
            cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
            switch(planarConfiguration) {
                case TIFFBaseline.PLANARCONFIG_CHUNKY:
                    return ImageTypeSpecifiers.createInterleaved(cs, new int[] { 0, 1, 2 }, dataType, false, false);
                case TIFFExtension.PLANARCONFIG_PLANAR:
                //return ImageTypeSpecifiers.createBanded(cs, new int[] {0, 1, 2}, new int[] {0, 0, 0}, dataType, false, false);
                default:
                    throw new IIOException(String.format("Unsupported PlanarConfiguration for Lab color TIFF (expected 1): %d", planarConfiguration));
            }
        case TIFFBaseline.PHOTOMETRIC_MASK:
        // TODO: Treat as grey?
        case TIFFCustom.PHOTOMETRIC_LOGL:
        case TIFFCustom.PHOTOMETRIC_LOGLUV:
        // Log
        case TIFFCustom.PHOTOMETRIC_CFA:
        case TIFFCustom.PHOTOMETRIC_LINEAR_RAW:
            // RAW (DNG)
            throw new IIOException("Unsupported TIFF PhotometricInterpretation value: " + interpretation);
        default:
            throw new IIOException("Unknown TIFF PhotometricInterpretation value: " + interpretation);
    }
}
Example 4
Project: xml-graphics-commons-master  File: ImageLoaderImageIO.java View source code
/** {@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 {
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                reader.setInput(imgStream, false, ignoreMetadata);
                ImageReadParam param = getParam(reader, hints);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    //                        if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                    imageData = reader.read(pageIndex, param);
                    //                        }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    //Quit early, we have the image
                    break;
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    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;
                    //Clear exception after successful fallback attempt
                    firstException = null;
                    break;
                } catch (IIOException iioe) {
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        XmlSourceUtil.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);
                try {
                    BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                    imageData = bi;
                    cm = cm2;
                } catch (IllegalArgumentException iae) {
                    String msg = "Image " + info.getOriginalURI() + " has an incompatible color profile." + " The color profile will be ignored." + "\nColor model of loaded bitmap: " + cm + "\nColor model of color profile: " + cm2;
                    if (info.getCustomObjects().get("warningincustomobject") != null) {
                        info.getCustomObjects().put("warning", msg);
                    } else {
                        log.warn(msg);
                    }
                }
            }
        }
        // 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.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);
    }
}
Example 5
Project: pdfbox-master  File: CatalogValidationProcess.java View source code
/**
     * This method checks the destOutputProfile which must be a valid ICCProfile.
     * 
     * If an other ICCProfile exists in the mapDestOutputProfile, a ValdiationError
     * (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE) is returned because of only one profile is authorized. If the
     * ICCProfile already exist in the mapDestOutputProfile, the method returns null. If the destOutputProfile contains
     * an invalid ICCProfile, a ValidationError (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID) is returned If the
     * destOutputProfile is an empty stream, a ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY) is returned.
     * 
     * If the destOutputFile is valid, mapDestOutputProfile is updated, the ICCProfile is added to the document ctx and
     * null is returned.
     * 
     * @param destOutputProfile
     * @param mapDestOutputProfile
     * @param ctx the preflight context.
     * @throws ValidationException
     */
protected void validateICCProfile(COSBase destOutputProfile, Map<COSObjectKey, Boolean> mapDestOutputProfile, PreflightContext ctx) throws ValidationException {
    try {
        if (destOutputProfile == null) {
            return;
        }
        // destOutputProfile should be an instance of COSObject because of this is a object reference
        if (destOutputProfile instanceof COSObject) {
            if (mapDestOutputProfile.containsKey(new COSObjectKey((COSObject) destOutputProfile))) {
                // the profile is already checked. continue
                return;
            } else if (!mapDestOutputProfile.isEmpty()) {
                // A DestOutputProfile exits but it isn't the same, error
                addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE, "More than one ICCProfile is defined"));
                return;
            }
        // else the profile will be kept in the tmpDestOutputProfile if it is valid
        }
        // keep reference to avoid multiple profile definition
        mapDestOutputProfile.put(new COSObjectKey((COSObject) destOutputProfile), true);
        COSDocument cosDocument = ctx.getDocument().getDocument();
        COSStream stream = COSUtils.getAsStream(destOutputProfile, cosDocument);
        if (stream == null) {
            addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object"));
            return;
        }
        InputStream is = stream.createInputStream();
        ICC_Profile iccp = null;
        try {
            iccp = ICC_Profile.getInstance(is);
        } finally {
            is.close();
        }
        if (!validateICCProfileNEntry(stream, ctx, iccp)) {
            return;
        }
        if (!validateICCProfileVersion(iccp, ctx)) {
            return;
        }
        if (ctx.getIccProfileWrapper() == null) {
            ctx.setIccProfileWrapper(new ICCProfileWrapper(iccp));
        }
    } catch (IllegalArgumentException e) {
        addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "DestOutputProfile isn't a valid ICCProfile: " + e.getMessage(), e));
    } catch (IOException e) {
        throw new ValidationException("Unable to parse the ICC Profile.", e);
    }
}
Example 6
Project: simpleimage-master  File: JPEGDecoder.java View source code
protected ColorSpace getColorSpace() {
    ColorSpace cs = null;
    if (supportICC) {
        if (extendImageHeader.isExistProfile()) {
            ICC_Profile profile = null;
            try {
                synchronized (ICC_Profile.class) {
                    profile = ICC_Profile.getInstance(extendImageHeader.getProfileData());
                }
            } catch (Exception ignore) {
                profile = null;
            }
            if (profile != null) {
                try {
                    cs = new ICC_ColorSpace(profile);
                } catch (Exception ignore) {
                    cs = null;
                }
            }
        }
    }
    // or doesn't exists ICC_Profile
    if (cs == null) {
        extendImageHeader.setExistProfile(false);
        if (rawImage.getColorspace() == JPEGColorSpace.CMYK) {
            cs = CMMColorSpace.getInstance(ColorSpace.TYPE_CMYK);
        } else if (rawImage.getColorspace() == JPEGColorSpace.RGB) {
            cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        } else {
            cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        }
    }
    return cs;
}
Example 7
Project: gatein-shindig-master  File: JPEGOptimizer.java View source code
public static BufferedImage readJpeg(InputStream is) throws ImageReadException, IOException {
    byte[] bytes = IOUtils.toByteArray(is);
    // We cant use Sanselan to read JPEG but we can use it to read all the metadata which is
    // where most security issues reside anyway in ImageIO
    Sanselan.getMetadata(bytes, null);
    byte[] iccBytes = Sanselan.getICCProfileBytes(bytes);
    if (iccBytes != null && iccBytes.length > 0) {
        ICC_Profile iccProfile = Sanselan.getICCProfile(bytes, null);
        if (iccProfile == null) {
            throw new ImageReadException("Image has ICC but it is corrupt and cannot be read");
        }
    }
    return ImageIO.read(new ByteArrayInputStream(bytes));
}
Example 8
Project: Latipics-master  File: Sanselan.java View source code
protected static ICC_Profile getICCProfile(ByteSource byteSource, Map params) throws ImageReadException, IOException {
    byte bytes[] = getICCProfileBytes(byteSource, params);
    if (bytes == null)
        return null;
    IccProfileParser parser = new IccProfileParser();
    IccProfileInfo info = parser.getICCProfileInfo(bytes);
    if (info.issRGB())
        return null;
    ICC_Profile icc = ICC_Profile.getInstance(bytes);
    return icc;
}
Example 9
Project: openjdk8-jdk-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 10
Project: sanselan-master  File: Sanselan.java View source code
protected static ICC_Profile getICCProfile(ByteSource byteSource, Map params) throws ImageReadException, IOException {
    byte bytes[] = getICCProfileBytes(byteSource, params);
    if (bytes == null)
        return null;
    IccProfileParser parser = new IccProfileParser();
    IccProfileInfo info = parser.getICCProfileInfo(bytes);
    if (info == null)
        return null;
    if (info.issRGB())
        return null;
    ICC_Profile icc = ICC_Profile.getInstance(bytes);
    return icc;
}
Example 11
Project: smartly-master  File: Imaging.java View source code
protected static ICC_Profile getICCProfile(final ByteSource byteSource, final Map<String, Object> params) throws ImageReadException, IOException {
    final byte bytes[] = getICCProfileBytes(byteSource, params);
    if (bytes == null) {
        return null;
    }
    final IccProfileParser parser = new IccProfileParser();
    final IccProfileInfo info = parser.getICCProfileInfo(bytes);
    if (info == null) {
        return null;
    }
    if (info.issRGB()) {
        return null;
    }
    final ICC_Profile icc = ICC_Profile.getInstance(bytes);
    return icc;
}
Example 12
Project: acs-aem-commons-master  File: CMYKJPEGImageReader.java View source code
public static BufferedImage read(ImageInputStream in, boolean inverseYCCKColors) throws IOException {
    // Seek to start of input stream
    in.seek(0);
    // Extract metadata from the JFIF stream.
    // --------------------------------------
    // In particular, we are interested into the following fields:
    int samplePrecision = 0;
    int numberOfLines = 0;
    int numberOfSamplesPerLine = 0;
    int numberOfComponentsInFrame = 0;
    int app14AdobeColorTransform = 0;
    ByteArrayOutputStream app2ICCProfile = new ByteArrayOutputStream();
    // Browse for marker segments, and extract data from those
    // which are of interest.
    JFIFInputStream fifi = new JFIFInputStream(new ImageInputStreamAdapter(in));
    for (JFIFInputStream.Segment seg = fifi.getNextSegment(); seg != null; seg = fifi.getNextSegment()) {
        if (0xffc0 <= seg.marker && seg.marker <= 0xffc3 || 0xffc5 <= seg.marker && seg.marker <= 0xffc7 || 0xffc9 <= seg.marker && seg.marker <= 0xffcb || 0xffcd <= seg.marker && seg.marker <= 0xffcf) {
            // SOF0 - SOF15: Start of Frame Header marker segment
            DataInputStream dis = new DataInputStream(fifi);
            samplePrecision = dis.readUnsignedByte();
            numberOfLines = dis.readUnsignedShort();
            numberOfSamplesPerLine = dis.readUnsignedShort();
            numberOfComponentsInFrame = dis.readUnsignedByte();
            // Thus we can abort here.
            break;
        } else if (seg.marker == 0xffe2) {
            // APP2: Application-specific marker segment
            if (seg.length >= 26) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 12-bytes containing the null-terminated string: "ICC_PROFILE".
                if (dis.readLong() == 0x4943435f50524f46L && dis.readInt() == 0x494c4500) {
                    // Skip 2 bytes
                    dis.skipBytes(2);
                    // Read Adobe ICC_PROFILE int buffer. The profile is split up over
                    // multiple APP2 marker segments.
                    byte[] b = new byte[512];
                    for (int count = dis.read(b); count != -1; count = dis.read(b)) {
                        app2ICCProfile.write(b, 0, count);
                    }
                }
            }
        } else if (seg.marker == 0xffee) {
            // APP14: Application-specific marker segment
            if (seg.length == 12) {
                //NOPMD
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 6-bytes containing the null-terminated string: "Adobe".
                if (dis.readInt() == 0x41646f62L && dis.readUnsignedShort() == 0x6500) {
                    int version = dis.readUnsignedByte();
                    int app14Flags0 = dis.readUnsignedShort();
                    int app14Flags1 = dis.readUnsignedShort();
                    app14AdobeColorTransform = dis.readUnsignedByte();
                }
            }
        }
    }
    //fifi.close();
    // Read the image data
    BufferedImage img = null;
    if (numberOfComponentsInFrame != 4) {
        // Read image with YUV color encoding.
        in.seek(0);
        img = readImageFromYUVorGray(in);
    } else if (numberOfComponentsInFrame == 4) {
        // Try to instantiate an ICC_Profile from the app2ICCProfile
        ICC_Profile profile = null;
        if (app2ICCProfile.size() > 0) {
            try {
                profile = ICC_Profile.getInstance(new ByteArrayInputStream(app2ICCProfile.toByteArray()));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        // In case of failure, use a Generic CMYK profile
        if (profile == null) {
            profile = ICC_Profile.getInstance(CMYKJPEGImageReader.class.getResourceAsStream("Generic CMYK Profile.icc"));
        }
        switch(app14AdobeColorTransform) {
            case 0:
            default:
                // Read image with RGBA color encoding.
                in.seek(0);
                img = readRGBAImageFromRGBA(new ImageInputStreamAdapter(in), profile);
                break;
            case 1:
                throw new IOException("YCbCr not supported");
            case 2:
                // Read image with inverted YCCK color encoding.
                // FIXME - How do we determine from the JFIF file whether
                // YCCK colors are inverted?
                in.seek(0);
                if (inverseYCCKColors) {
                    img = readRGBImageFromInvertedYCCK(new ImageInputStreamAdapter(in), profile);
                } else {
                    img = readRGBImageFromYCCK(new ImageInputStreamAdapter(in), profile);
                }
                break;
        }
    }
    return img;
}
Example 13
Project: fop-master  File: ColorUtil.java View source code
/**
     * Parse a color specified using the fop-rgb-named-color() function.
     *
     * @param value the function call
     * @return a color if possible
     * @throws PropertyException if the format is wrong.
     */
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException {
    Color parsedColor;
    int poss = value.indexOf("(");
    int pose = value.indexOf(")");
    if (poss != -1 && pose != -1) {
        String[] args = value.substring(poss + 1, pose).split(",");
        try {
            if (args.length != 6) {
                throw new PropertyException("rgb-named-color() function must have 6 arguments");
            }
            //Set up fallback sRGB value
            Color sRGB = parseFallback(args, value);
            /* Get and verify ICC profile name */
            String iccProfileName = args[3].trim();
            if (iccProfileName == null || "".equals(iccProfileName)) {
                throw new PropertyException("ICC profile name missing");
            }
            ICC_ColorSpace colorSpace = null;
            String iccProfileSrc;
            if (isPseudoProfile(iccProfileName)) {
                throw new IllegalArgumentException("Pseudo-profiles are not allowed with fop-rgb-named-color()");
            } else {
                /* Get and verify ICC profile source */
                iccProfileSrc = args[4].trim();
                if (iccProfileSrc == null || "".equals(iccProfileSrc)) {
                    throw new PropertyException("ICC profile source missing");
                }
                iccProfileSrc = unescapeString(iccProfileSrc);
            }
            // color name
            String colorName = unescapeString(args[5].trim());
            /* Ask FOP factory to get ColorSpace for the specified ICC profile source */
            if (foUserAgent != null && iccProfileSrc != null) {
                RenderingIntent renderingIntent = RenderingIntent.AUTO;
                //TODO connect to fo:color-profile/@rendering-intent
                colorSpace = (ICC_ColorSpace) foUserAgent.getColorSpaceCache().get(iccProfileName, iccProfileSrc, renderingIntent);
            }
            if (colorSpace != null) {
                ICC_Profile profile = colorSpace.getProfile();
                if (NamedColorProfileParser.isNamedColorProfile(profile)) {
                    NamedColorProfileParser parser = new NamedColorProfileParser();
                    NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc);
                    NamedColorSpace ncs = ncp.getNamedColor(colorName);
                    if (ncs != null) {
                        parsedColor = new ColorWithFallback(ncs, new float[] { 1.0f }, 1.0f, null, sRGB);
                    } else {
                        log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc);
                        parsedColor = sRGB;
                    }
                } else {
                    log.warn("ICC profile is no named color profile: " + iccProfileSrc);
                    parsedColor = sRGB;
                }
            } else {
                // ICC profile could not be loaded - use rgb replacement values */
                log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values.");
                parsedColor = sRGB;
            }
        } catch (IOException ioe) {
            throw new PropertyException(ioe);
        } catch (RuntimeException re) {
            throw new PropertyException(re);
        }
    } else {
        throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)");
    }
    return parsedColor;
}
Example 14
Project: jdk7u-jdk-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 15
Project: lenient-pdf-compare-master  File: PDFColorSpace.java View source code
/**
     * Get a color space specified in a PDFObject
     *
     * @param csobj the PDFObject with the colorspace information
     */
public static PDFColorSpace getColorSpace(PDFObject csobj, Map resources) throws IOException {
    String name;
    PDFObject colorSpaces = null;
    if (resources != null) {
        colorSpaces = (PDFObject) resources.get("ColorSpace");
    }
    if (csobj.getType() == PDFObject.NAME) {
        name = csobj.getStringValue();
        if (name.equals("DeviceGray") || name.equals("G")) {
            return getColorSpace(COLORSPACE_GRAY);
        } else if (name.equals("DeviceRGB") || name.equals("RGB")) {
            return getColorSpace(COLORSPACE_RGB);
        } else if (name.equals("DeviceCMYK") || name.equals("CMYK")) {
            return getColorSpace(COLORSPACE_CMYK);
        } else if (name.equals("Pattern")) {
            return getColorSpace(COLORSPACE_PATTERN);
        } else if (colorSpaces != null) {
            csobj = (PDFObject) colorSpaces.getDictRef(name);
        }
    }
    if (csobj == null) {
        return null;
    } else if (csobj.getCache() != null) {
        return (PDFColorSpace) csobj.getCache();
    }
    PDFColorSpace value = null;
    // csobj is [/name <<dict>>]
    PDFObject[] ary = csobj.getArray();
    name = ary[0].getStringValue();
    if (name.equals("CalGray")) {
        value = new PDFColorSpace(new CalGrayColor(ary[1]));
    } else if (name.equals("CalRGB")) {
        value = new PDFColorSpace(new CalRGBColor(ary[1]));
    } else if (name.equals("Lab")) {
        value = new PDFColorSpace(new LabColor(ary[1]));
    } else if (name.equals("ICCBased")) {
        ByteArrayInputStream bais = new ByteArrayInputStream(ary[1].getStream());
        ICC_Profile profile = ICC_Profile.getInstance(bais);
        value = new PDFColorSpace(new ICC_ColorSpace(profile));
    } else if (name.equals("Separation") || name.equals("DeviceN")) {
        PDFColorSpace alternate = getColorSpace(ary[2], resources);
        PDFFunction function = PDFFunction.getFunction(ary[3]);
        value = new AlternateColorSpace(alternate, function);
    } else if (name.equals("Indexed") || name.equals("I")) {
        /**
             * 4.5.5 [/Indexed baseColor hival lookup]
             */
        PDFColorSpace refspace = getColorSpace(ary[1], resources);
        // number of indices= ary[2], data is in ary[3];
        int count = ary[2].getIntValue();
        value = new IndexedColor(refspace, count, ary[3]);
    } else if (name.equals("Pattern")) {
        if (ary.length == 1) {
            return getColorSpace(COLORSPACE_PATTERN);
        }
        PDFColorSpace base = getColorSpace(ary[1], resources);
        return new PatternSpace(base);
    } else {
        throw new PDFParseException("Unknown color space: " + name + " with " + ary[1]);
    }
    csobj.setCache(value);
    return value;
}
Example 16
Project: ManagedRuntimeInitiative-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 17
Project: VirtMus-master  File: ICCBased.java View source code
/**
     *
     */
public synchronized void init() {
    if (inited) {
        return;
    }
    inited = true;
    byte[] in;
    try {
        stream.init();
        in = stream.getDecodedStreamBytes(0);
        if (logger.isLoggable(Level.FINEST)) {
            String content = Utils.convertByteArrayToByteString(in);
            logger.finest("Content = " + content);
        }
        if (in != null) {
            ICC_Profile profile = ICC_Profile.getInstance(in);
            colorSpace = new ICC_ColorSpace(profile);
        }
    } catch (Exception e) {
        logger.log(Level.FINE, "Error Processing ICCBased Colour Profile", e);
    }
}
Example 18
Project: batik-master  File: SVGImageElementBridge.java View source code
/**
     * Analyzes the color-profile property and builds an ICCColorSpaceExt
     * object from it.
     *
     * @param element the element with the color-profile property
     * @param ctx the bridge context
     */
protected static ICCColorSpaceWithIntent extractColorSpace(Element element, BridgeContext ctx) {
    String colorProfileProperty = CSSUtilities.getComputedStyle(element, SVGCSSEngine.COLOR_PROFILE_INDEX).getStringValue();
    // The only cases that need special handling are 'sRGB' and 'name'
    ICCColorSpaceWithIntent colorSpace = null;
    if (CSS_SRGB_VALUE.equalsIgnoreCase(colorProfileProperty)) {
        colorSpace = new ICCColorSpaceWithIntent(ICC_Profile.getInstance(ColorSpace.CS_sRGB), RenderingIntent.AUTO, "sRGB", null);
    } else if (!CSS_AUTO_VALUE.equalsIgnoreCase(colorProfileProperty) && !"".equalsIgnoreCase(colorProfileProperty)) {
        // The value is neither 'sRGB' nor 'auto': it is a profile name.
        SVGColorProfileElementBridge profileBridge = (SVGColorProfileElementBridge) ctx.getBridge(SVG_NAMESPACE_URI, SVG_COLOR_PROFILE_TAG);
        if (profileBridge != null) {
            colorSpace = profileBridge.createICCColorSpaceWithIntent(ctx, element, colorProfileProperty);
        }
    }
    return colorSpace;
}
Example 19
Project: celements-photo-master  File: DecodeImageCommand.java View source code
public BufferedImage readImage(XWikiAttachment att, XWikiContext context) throws IOException, ImageReadException, XWikiException {
    colorType = COLOR_TYPE_RGB;
    boolean hasAdobeMarker = false;
    ImageInputStream stream = ImageIO.createImageInputStream(att.getContentInputStream(context));
    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
    while (iter.hasNext()) {
        ImageReader reader = iter.next();
        reader.setInput(stream);
        BufferedImage image;
        ICC_Profile profile = null;
        try {
            try {
                image = reader.read(0);
            } catch (CMMException cmmExcp) {
                image = readUsingJAI(att, context);
            }
        } catch (IIOException iioExcp) {
            colorType = COLOR_TYPE_CMYK;
            hasAdobeMarker = hasAdobeMarker(att.getContentInputStream(context), att.getFilename());
            profile = Sanselan.getICCProfile(att.getContentInputStream(context), att.getFilename());
            WritableRaster raster = (WritableRaster) reader.readRaster(0, null);
            if (colorType == COLOR_TYPE_YCCK) {
                convertYcckToCmyk(raster);
            }
            if (hasAdobeMarker) {
                convertInvertedColors(raster);
            }
            image = convertCmykToRgb(raster, profile);
        }
        return image;
    }
    return null;
}
Example 20
Project: consulo-master  File: MacOSApplicationProvider.java View source code
private static ColorSpace initializeNativeColorSpace() {
    InputStream is = null;
    try {
        is = new FileInputStream(GENERIC_RGB_PROFILE_PATH);
        ICC_Profile profile = ICC_Profile.getInstance(is);
        return new ICC_ColorSpace(profile);
    } catch (Throwable e) {
        LOG.warn("Couldn't load generic RGB color profile", e);
        return null;
    } finally {
        StreamUtil.closeStream(is);
    }
}
Example 21
Project: dawn-third-master  File: CMYKJPEGImageReader.java View source code
public static BufferedImage read(ImageInputStream in, boolean inverseYCCKColors, boolean isIgnoreColorProfile) throws IOException {
    // Seek to start of input stream
    in.seek(0);
    // Extract metadata from the JFIF stream.
    // --------------------------------------
    // In particular, we are interested into the following fields:
    int samplePrecision = 0;
    int numberOfLines = 0;
    int numberOfSamplesPerLine = 0;
    int numberOfComponentsInFrame = 0;
    int app14AdobeColorTransform = 0;
    ByteArrayOutputStream app2ICCProfile = new ByteArrayOutputStream();
    // Browse for marker segments, and extract data from those
    // which are of interest.
    JFIFInputStream fifi = new JFIFInputStream(new ImageInputStreamAdapter(in));
    for (JFIFInputStream.Segment seg = fifi.getNextSegment(); seg != null; seg = fifi.getNextSegment()) {
        if (0xffc0 <= seg.marker && seg.marker <= 0xffc3 || 0xffc5 <= seg.marker && seg.marker <= 0xffc7 || 0xffc9 <= seg.marker && seg.marker <= 0xffcb || 0xffcd <= seg.marker && seg.marker <= 0xffcf) {
            // SOF0 - SOF15: Start of Frame Header marker segment
            DataInputStream dis = new DataInputStream(fifi);
            samplePrecision = dis.readUnsignedByte();
            numberOfLines = dis.readUnsignedShort();
            numberOfSamplesPerLine = dis.readUnsignedShort();
            numberOfComponentsInFrame = dis.readUnsignedByte();
            // Thus we can abort here.
            break;
        } else if (seg.marker == 0xffe2) {
            // APP2: Application-specific marker segment
            if (seg.length >= 26) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 12-bytes containing the null-terminated string: "ICC_PROFILE".
                if (dis.readLong() == 0x4943435f50524f46L && dis.readInt() == 0x494c4500) {
                    // Skip 2 bytes
                    dis.skipBytes(2);
                    // Read Adobe ICC_PROFILE int buffer. The profile is split up over
                    // multiple APP2 marker segments.
                    byte[] b = new byte[512];
                    for (int count = dis.read(b); count != -1; count = dis.read(b)) {
                        app2ICCProfile.write(b, 0, count);
                    }
                }
            }
        } else if (seg.marker == 0xffee) {
            // APP14: Application-specific marker segment
            if (seg.length == 12) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 6-bytes containing the null-terminated string: "Adobe".
                if (dis.readInt() == 0x41646f62L && dis.readUnsignedShort() == 0x6500) {
                    int version = dis.readUnsignedByte();
                    int app14Flags0 = dis.readUnsignedShort();
                    int app14Flags1 = dis.readUnsignedShort();
                    app14AdobeColorTransform = dis.readUnsignedByte();
                }
            }
        }
    }
    //fifi.close();
    // Read the image data
    BufferedImage img = null;
    if (numberOfComponentsInFrame != 4) {
        // Read image with YCC color encoding.
        in.seek(0);
        //            img = readImageFromYCCorGray(in);
        img = readRGBImageFromYCC(new ImageInputStreamAdapter(in), null);
    } else if (numberOfComponentsInFrame == 4) {
        // Try to instantiate an ICC_Profile from the app2ICCProfile
        ICC_Profile profile = null;
        if (!isIgnoreColorProfile && app2ICCProfile.size() > 0) {
            try {
                profile = ICC_Profile.getInstance(new ByteArrayInputStream(app2ICCProfile.toByteArray()));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        switch(app14AdobeColorTransform) {
            case 0:
            default:
                // Read image with RGBA color encoding.
                in.seek(0);
                img = readRGBAImageFromRGBA(new ImageInputStreamAdapter(in), profile);
                break;
            case 1:
                throw new IOException("YCbCr not supported");
            case 2:
                // I case none has been supplied, we create a default one here.
                if (profile == null) {
                    profile = ICC_Profile.getInstance(CMYKJPEGImageReader.class.getResourceAsStream("Generic CMYK Profile.icc"));
                }
                in.seek(0);
                if (inverseYCCKColors) {
                    img = readRGBImageFromInvertedYCCK(new ImageInputStreamAdapter(in), profile);
                } else {
                    img = readRGBImageFromYCCK(new ImageInputStreamAdapter(in), profile);
                }
                break;
        }
    }
    return img;
}
Example 22
Project: icepdf-master  File: DeviceCMYK.java View source code
/**
     * Gets the ICC Color Profile found in the icepdf-core.jar at the location
     * /org/icepdf/core/pobjects/graphics/res/ or the ICC Color Profiel
     * specified by the system property org.icepdf.core.pobjects.graphics.cmyk.
     *
     * @return associated ICC CMYK Color space.
     */
public static ICC_ColorSpace getIccCmykColorSpace() {
    // would prefer to only have one instance but becuase of JDK-8033238
    // we can run into decode issue if we share the profile across
    String customCMYKProfilePath = null;
    try {
        Object profileStream;
        customCMYKProfilePath = Defs.sysProperty("org.icepdf.core.pobjects.graphics.cmyk");
        if (customCMYKProfilePath == null) {
            customCMYKProfilePath = "/org/icepdf/core/pobjects/graphics/res/CoatedFOGRA27.icc";
            profileStream = DeviceCMYK.class.getResourceAsStream(customCMYKProfilePath);
        } else {
            profileStream = new FileInputStream(customCMYKProfilePath);
        }
        ICC_Profile icc_profile = ICC_Profile.getInstance((InputStream) profileStream);
        return new ICC_ColorSpace(icc_profile);
    } catch (Exception exception) {
        logger.warning("Error loading ICC color profile: " + customCMYKProfilePath);
    }
    return null;
}
Example 23
Project: ikvm-monotouch-master  File: ProfileHeader.java View source code
/**
   * Creates a header, setting the header file size at the same time.
   * @param size the profile file size.
   */
public byte[] getData(int size) {
    byte[] data = new byte[HEADERSIZE];
    ByteBuffer buf = ByteBuffer.wrap(data);
    buf.putInt(ICC_Profile.icHdrSize, size);
    buf.putInt(ICC_Profile.icHdrCmmId, cmmId);
    buf.putShort(ICC_Profile.icHdrVersion, (short) (majorVersion << 8 | minorVersion));
    for (int i = 1; i < classMap.length; i += 2) if (profileClass == classMap[i])
        buf.putInt(ICC_Profile.icHdrDeviceClass, classMap[i - 1]);
    for (int i = 1; i < csTypeMap.length; i += 2) if (csTypeMap[i] == colorSpace)
        buf.putInt(ICC_Profile.icHdrColorSpace, csTypeMap[i - 1]);
    for (int i = 1; i < csTypeMap.length; i += 2) if (csTypeMap[i] == profileColorSpace)
        buf.putInt(ICC_Profile.icHdrPcs, csTypeMap[i - 1]);
    System.arraycopy(timestamp, 0, data, ICC_Profile.icHdrDate, timestamp.length);
    buf.putInt(ICC_Profile.icHdrMagic, icMagicNumber);
    buf.putInt(ICC_Profile.icHdrPlatform, platform);
    buf.putInt(ICC_Profile.icHdrFlags, flags);
    buf.putInt(ICC_Profile.icHdrManufacturer, manufacturerSig);
    buf.putInt(ICC_Profile.icHdrModel, modelSig);
    System.arraycopy(attributes, 0, data, ICC_Profile.icHdrAttributes, attributes.length);
    buf.putInt(ICC_Profile.icHdrRenderingIntent, intent);
    System.arraycopy(illuminant, 0, data, ICC_Profile.icHdrIlluminant, illuminant.length);
    buf.putInt(ICC_Profile.icHdrCreator, creatorSig);
    return buf.array();
}
Example 24
Project: imageio-ext-master  File: TIFFImageReader.java View source code
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IIOException {
    Integer imageIndexInteger = Integer.valueOf(imageIndex);
    if (imageTypeMap.containsKey(imageIndexInteger))
        // Return the cached ITS List.
        return imageTypeMap.get(imageIndexInteger).iterator();
    // Create a new ITS List.
    final List<ImageTypeSpecifier> l = new ArrayList<ImageTypeSpecifier>();
    // Create the ITS and cache if for later use so that this method
    // always returns an Iterator containing the same ITS objects.
    seekToImage(imageIndex, true);
    ImageTypeSpecifier itsRaw = TIFFDecompressor.getRawImageTypeSpecifier(photometricInterpretation, compression, samplesPerPixel, bitsPerSample, sampleFormat, extraSamples, colorMap);
    // Check for an ICCProfile field.
    TIFFField iccProfileField = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ICC_PROFILE);
    // to use it if the data layout is component type.
    if (iccProfileField != null && itsRaw.getColorModel() instanceof ComponentColorModel) {
        // Create a ColorSpace from the profile.
        byte[] iccProfileValue = iccProfileField.getAsBytes();
        ICC_Profile iccProfile = ICC_Profile.getInstance(iccProfileValue);
        ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(iccProfile);
        // Get the raw sample and color information.
        ColorModel cmRaw = itsRaw.getColorModel();
        ColorSpace csRaw = cmRaw.getColorSpace();
        SampleModel smRaw = itsRaw.getSampleModel();
        // Get the number of samples per pixel and the number
        // of color components.
        int numBands = smRaw.getNumBands();
        int numComponents = iccColorSpace.getNumComponents();
        // numbers of samples and color components are amenable.
        if (numBands == numComponents || numBands == numComponents + 1) {
            // Set alpha flags.
            boolean hasAlpha = numComponents != numBands;
            boolean isAlphaPre = hasAlpha && cmRaw.isAlphaPremultiplied();
            // Create a ColorModel of the same class and with
            // the same transfer type.
            ColorModel iccColorModel = new ComponentColorModel(iccColorSpace, cmRaw.getComponentSize(), hasAlpha, isAlphaPre, cmRaw.getTransparency(), cmRaw.getTransferType());
            // Prepend the ICC profile-based ITS to the List. The
            // ColorModel and SampleModel are guaranteed to be
            // compatible as the old and new ColorModels are both
            // ComponentColorModels with the same transfer type
            // and the same number of components.
            l.add(new ImageTypeSpecifier(iccColorModel, smRaw));
            // as the ICC ColorSpace.
            if (csRaw.getType() == iccColorSpace.getType() && csRaw.getNumComponents() == iccColorSpace.getNumComponents()) {
                l.add(itsRaw);
            }
        } else {
            // ICCProfile not compatible with SampleModel.
            // Append the raw ITS to the List.
            l.add(itsRaw);
        }
    } else {
        // No ICCProfile field or raw ColorModel not component.
        // Append the raw ITS to the List.
        l.add(itsRaw);
    }
    // Cache the ITS List.
    imageTypeMap.put(imageIndexInteger, l);
    return l.iterator();
}
Example 25
Project: intellij-community-master  File: MacOSApplicationProvider.java View source code
private static ColorSpace initializeNativeColorSpace() {
    try (InputStream is = new FileInputStream(GENERIC_RGB_PROFILE_PATH)) {
        ICC_Profile profile = ICC_Profile.getInstance(is);
        return new ICC_ColorSpace(profile);
    } catch (Throwable e) {
        LOG.warn("Couldn't load generic RGB color profile", e);
        return null;
    }
}
Example 26
Project: jhotdraw-master  File: ColorUtil.java View source code
/**
     * Returns true, if the two color spaces are equal.
     */
public static boolean isEqual(ColorSpace a, ColorSpace b) {
    if ((a instanceof ICC_ColorSpace) && (b instanceof ICC_ColorSpace)) {
        ICC_ColorSpace aicc = (ICC_ColorSpace) a;
        ICC_ColorSpace bicc = (ICC_ColorSpace) b;
        ICC_Profile ap = aicc.getProfile();
        ICC_Profile bp = bicc.getProfile();
        return ap.equals(bp);
    } else {
        return a.equals(b);
    }
}
Example 27
Project: libbio-formats-java-master  File: TIFFImageReader.java View source code
public Iterator getImageTypes(int imageIndex) throws IIOException {
    // List of ImageTypeSpecifiers
    List l;
    Integer imageIndexInteger = new Integer(imageIndex);
    if (imageTypeMap.containsKey(imageIndexInteger)) {
        // Return the cached ITS List.
        l = (List) imageTypeMap.get(imageIndexInteger);
    } else {
        // Create a new ITS List.
        l = new ArrayList(1);
        // Create the ITS and cache if for later use so that this method
        // always returns an Iterator containing the same ITS objects.
        seekToImage(imageIndex);
        ImageTypeSpecifier itsRaw = TIFFDecompressor.getRawImageTypeSpecifier(photometricInterpretation, compression, samplesPerPixel, bitsPerSample, sampleFormat, extraSamples, colorMap);
        // Check for an ICCProfile field.
        TIFFField iccProfileField = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ICC_PROFILE);
        // to use it if the data layout is component type.
        if (iccProfileField != null && itsRaw.getColorModel() instanceof ComponentColorModel) {
            // Create a ColorSpace from the profile.
            byte[] iccProfileValue = iccProfileField.getAsBytes();
            ICC_Profile iccProfile = ICC_Profile.getInstance(iccProfileValue);
            ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(iccProfile);
            // Get the raw sample and color information.
            ColorModel cmRaw = itsRaw.getColorModel();
            ColorSpace csRaw = cmRaw.getColorSpace();
            SampleModel smRaw = itsRaw.getSampleModel();
            // Get the number of samples per pixel and the number
            // of color components.
            int numBands = smRaw.getNumBands();
            int numComponents = iccColorSpace.getNumComponents();
            // numbers of samples and color components are amenable.
            if (numBands == numComponents || numBands == numComponents + 1) {
                // Set alpha flags.
                boolean hasAlpha = numComponents != numBands;
                boolean isAlphaPre = hasAlpha && cmRaw.isAlphaPremultiplied();
                // Create a ColorModel of the same class and with
                // the same transfer type.
                ColorModel iccColorModel = new ComponentColorModel(iccColorSpace, cmRaw.getComponentSize(), hasAlpha, isAlphaPre, cmRaw.getTransparency(), cmRaw.getTransferType());
                // Prepend the ICC profile-based ITS to the List. The
                // ColorModel and SampleModel are guaranteed to be
                // compatible as the old and new ColorModels are both
                // ComponentColorModels with the same transfer type
                // and the same number of components.
                l.add(new ImageTypeSpecifier(iccColorModel, smRaw));
                // as the ICC ColorSpace.
                if (csRaw.getType() == iccColorSpace.getType() && csRaw.getNumComponents() == iccColorSpace.getNumComponents()) {
                    l.add(itsRaw);
                }
            } else {
                // ICCProfile not compatible with SampleModel.
                // Append the raw ITS to the List.
                l.add(itsRaw);
            }
        } else {
            // No ICCProfile field or raw ColorModel not component.
            // Append the raw ITS to the List.
            l.add(itsRaw);
        }
        // Cache the ITS List.
        imageTypeMap.put(imageIndexInteger, l);
    }
    return l.iterator();
}
Example 28
Project: PDFrenderer-master  File: PDFColorSpace.java View source code
/**
     * Get a color space specified in a PDFObject
     *
     * @param csobj the PDFObject with the colorspace information
     */
public static PDFColorSpace getColorSpace(PDFObject csobj, Map resources) throws IOException {
    String name;
    PDFObject colorSpaces = null;
    if (resources != null) {
        colorSpaces = (PDFObject) resources.get("ColorSpace");
    }
    if (csobj.getType() == PDFObject.NAME) {
        name = csobj.getStringValue();
        if (name.equals("DeviceGray") || name.equals("G")) {
            return getColorSpace(COLORSPACE_GRAY);
        } else if (name.equals("DeviceRGB") || name.equals("RGB")) {
            return getColorSpace(COLORSPACE_RGB);
        } else if (name.equals("DeviceCMYK") || name.equals("CMYK")) {
            return getColorSpace(COLORSPACE_CMYK);
        } else if (name.equals("Pattern")) {
            return getColorSpace(COLORSPACE_PATTERN);
        } else if (colorSpaces != null) {
            csobj = colorSpaces.getDictRef(name);
        }
    }
    if (csobj == null) {
        return null;
    } else if (csobj.getCache() != null) {
        return (PDFColorSpace) csobj.getCache();
    }
    PDFColorSpace value = null;
    // csobj is [/name <<dict>>]
    PDFObject[] ary = csobj.getArray();
    name = ary[0].getStringValue();
    if (name.equals("DeviceGray") || name.equals("G")) {
        return getColorSpace(COLORSPACE_GRAY);
    } else if (name.equals("DeviceRGB") || name.equals("RGB")) {
        return getColorSpace(COLORSPACE_RGB);
    } else if (name.equals("DeviceCMYK") || name.equals("CMYK")) {
        return getColorSpace(COLORSPACE_CMYK);
    } else if (name.equals("CalGray")) {
        value = new PDFColorSpace(new CalGrayColor(ary[1]));
    } else if (name.equals("CalRGB")) {
        value = new PDFColorSpace(new CalRGBColor(ary[1]));
    } else if (name.equals("Lab")) {
        value = new PDFColorSpace(new LabColor(ary[1]));
    } else if (name.equals("ICCBased")) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(ary[1].getStream());
            ICC_Profile profile = ICC_Profile.getInstance(bais);
            value = new PDFColorSpace(new ICC_ColorSpace(profile));
        } catch (IllegalArgumentException e) {
            return getColorSpace(COLORSPACE_RGB);
        }
    } else if (name.equals("Separation") || name.equals("DeviceN")) {
        PDFColorSpace alternate = getColorSpace(ary[2], resources);
        PDFFunction function = PDFFunction.getFunction(ary[3]);
        value = new AlternateColorSpace(alternate, function);
    } else if (name.equals("Indexed") || name.equals("I")) {
        /**
             * 4.5.5 [/Indexed baseColor hival lookup]
             */
        PDFColorSpace refspace = getColorSpace(ary[1], resources);
        // number of indices= ary[2], data is in ary[3];
        int count = ary[2].getIntValue();
        try {
            value = new IndexedColor(refspace, count, ary[3]);
        } catch (Exception e) {
            value = refspace;
        }
    } else if (name.equals("Pattern")) {
        if (ary.length == 1) {
            return getColorSpace(COLORSPACE_PATTERN);
        }
        PDFColorSpace base = getColorSpace(ary[1], resources);
        return new PatternSpace(base);
    } else if (name.equals("DeviceRGB")) {
        return getColorSpace(COLORSPACE_RGB);
    } else if (name.equals("DeviceCMYK")) {
        return getColorSpace(COLORSPACE_CMYK);
    } else {
        // removed access to ary[1] dur to index out of bounds exceptions
        throw new PDFParseException("Unknown color space: " + name);
    }
    csobj.setCache(value);
    return value;
}
Example 29
Project: scriptographer-master  File: Color.java View source code
/**
	 * Call first nativeGetProfile in order to get the illustrator's profile,
	 * and if this doesn't work, it falls back to the scriptographer's internal
	 * profiles.
	 * 
	 * @param model
	 */
protected static ICC_Profile getProfile(ColorModel model) {
    // first try the illustrator internal WS profiles:
    ICC_Profile profile = nativeGetProfile(model.value);
    if (profile == null) {
        // if this didn't work, use scriptographer's internal profiles:
        try {
            profile = ICC_Profile.getInstance(Color.class.getClassLoader().getResourceAsStream("com/scriptographer/cmm/" + model.name().toLowerCase() + ".icc"));
        } catch (IOException e) {
            throw new ScriptographerException(e);
        }
    }
    return profile;
}
Example 30
Project: selenium-utils-master  File: CMYKJPEGImageReader.java View source code
public static BufferedImage read(ImageInputStream in, boolean inverseYCCKColors, boolean isIgnoreColorProfile) throws IOException {
    // Seek to start of input stream
    in.seek(0);
    // Extract metadata from the JFIF stream.
    // --------------------------------------
    // In particular, we are interested into the following fields:
    int samplePrecision = 0;
    int numberOfLines = 0;
    int numberOfSamplesPerLine = 0;
    int numberOfComponentsInFrame = 0;
    int app14AdobeColorTransform = 0;
    ByteArrayOutputStream app2ICCProfile = new ByteArrayOutputStream();
    // Browse for marker segments, and extract data from those
    // which are of interest.
    JFIFInputStream fifi = new JFIFInputStream(new ImageInputStreamAdapter(in));
    for (JFIFInputStream.Segment seg = fifi.getNextSegment(); seg != null; seg = fifi.getNextSegment()) {
        if (0xffc0 <= seg.marker && seg.marker <= 0xffc3 || 0xffc5 <= seg.marker && seg.marker <= 0xffc7 || 0xffc9 <= seg.marker && seg.marker <= 0xffcb || 0xffcd <= seg.marker && seg.marker <= 0xffcf) {
            // SOF0 - SOF15: Start of Frame Header marker segment
            DataInputStream dis = new DataInputStream(fifi);
            samplePrecision = dis.readUnsignedByte();
            numberOfLines = dis.readUnsignedShort();
            numberOfSamplesPerLine = dis.readUnsignedShort();
            numberOfComponentsInFrame = dis.readUnsignedByte();
            // Thus we can abort here.
            break;
        } else if (seg.marker == 0xffe2) {
            // APP2: Application-specific marker segment
            if (seg.length >= 26) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 12-bytes containing the null-terminated string: "ICC_PROFILE".
                if (dis.readLong() == 0x4943435f50524f46L && dis.readInt() == 0x494c4500) {
                    // Skip 2 bytes
                    dis.skipBytes(2);
                    // Read Adobe ICC_PROFILE int buffer. The profile is split up over
                    // multiple APP2 marker segments.
                    byte[] b = new byte[512];
                    for (int count = dis.read(b); count != -1; count = dis.read(b)) {
                        app2ICCProfile.write(b, 0, count);
                    }
                }
            }
        } else if (seg.marker == 0xffee) {
            // APP14: Application-specific marker segment
            if (seg.length == 12) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 6-bytes containing the null-terminated string: "Adobe".
                if (dis.readInt() == 0x41646f62L && dis.readUnsignedShort() == 0x6500) {
                    int version = dis.readUnsignedByte();
                    int app14Flags0 = dis.readUnsignedShort();
                    int app14Flags1 = dis.readUnsignedShort();
                    app14AdobeColorTransform = dis.readUnsignedByte();
                }
            }
        }
    }
    //fifi.close();
    // Read the image data
    BufferedImage img = null;
    if (numberOfComponentsInFrame != 4) {
        // Read image with YCC color encoding.
        in.seek(0);
        //            img = readImageFromYCCorGray(in);
        img = readRGBImageFromYCC(new ImageInputStreamAdapter(in), null);
    } else if (numberOfComponentsInFrame == 4) {
        // Try to instantiate an ICC_Profile from the app2ICCProfile
        ICC_Profile profile = null;
        if (!isIgnoreColorProfile && app2ICCProfile.size() > 0) {
            try {
                profile = ICC_Profile.getInstance(new ByteArrayInputStream(app2ICCProfile.toByteArray()));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        switch(app14AdobeColorTransform) {
            case 0:
            default:
                // Read image with RGBA color encoding.
                in.seek(0);
                img = readRGBAImageFromRGBA(new ImageInputStreamAdapter(in), profile);
                break;
            case 1:
                throw new IOException("YCbCr not supported");
            case 2:
                // I case none has been supplied, we create a default one here.
                if (profile == null) {
                    profile = ICC_Profile.getInstance(CMYKJPEGImageReader.class.getResourceAsStream("Generic CMYK Profile.icc"));
                }
                in.seek(0);
                if (inverseYCCKColors) {
                    img = readRGBImageFromInvertedYCCK(new ImageInputStreamAdapter(in), profile);
                } else {
                    img = readRGBImageFromYCCK(new ImageInputStreamAdapter(in), profile);
                }
                break;
        }
    }
    return img;
}
Example 31
Project: bioformats-master  File: BMPImageReader.java View source code
public void readHeader() throws IOException {
    if (gotHeader) {
        // Seek to where the image data starts, since that is where
        // the stream pointer should be after header is read
        iis.seek(imageDataOffset);
        return;
    }
    if (iis == null) {
        throw new IllegalStateException(I18N.getString("BMPImageReader5"));
    }
    int profileData = 0, profileSize = 0;
    this.metadata = new BMPMetadata();
    iis.mark();
    // read and check the magic marker
    byte[] marker = new byte[2];
    iis.read(marker);
    if (marker[0] != 0x42 || marker[1] != 0x4d)
        throw new IllegalArgumentException(I18N.getString("BMPImageReader1"));
    // Read file size
    bitmapFileSize = iis.readUnsignedInt();
    // skip the two reserved fields
    iis.skipBytes(4);
    // Offset to the bitmap from the beginning
    bitmapOffset = iis.readUnsignedInt();
    // End File Header
    // Start BitmapCoreHeader
    long size = iis.readUnsignedInt();
    if (size == 12) {
        width = iis.readShort();
        height = iis.readShort();
    } else {
        width = iis.readInt();
        height = iis.readInt();
    }
    metadata.width = width;
    metadata.height = height;
    int planes = iis.readUnsignedShort();
    bitsPerPixel = iis.readUnsignedShort();
    //metadata.colorPlane = planes;
    metadata.bitsPerPixel = (short) bitsPerPixel;
    // As BMP always has 3 rgb bands, except for Version 5,
    // which is bgra
    numBands = 3;
    if (size == 12) {
        // Windows 2.x and OS/2 1.x
        metadata.bmpVersion = VERSION_2;
        // Classify the image type
        if (bitsPerPixel == 1) {
            imageType = VERSION_2_1_BIT;
        } else if (bitsPerPixel == 4) {
            imageType = VERSION_2_4_BIT;
        } else if (bitsPerPixel == 8) {
            imageType = VERSION_2_8_BIT;
        } else if (bitsPerPixel == 24) {
            imageType = VERSION_2_24_BIT;
        }
        // Read in the palette
        int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 3);
        int sizeOfPalette = numberOfEntries * 3;
        palette = new byte[sizeOfPalette];
        iis.readFully(palette, 0, sizeOfPalette);
        metadata.palette = palette;
        metadata.paletteSize = numberOfEntries;
    } else {
        compression = iis.readUnsignedInt();
        imageSize = iis.readUnsignedInt();
        long xPelsPerMeter = iis.readInt();
        long yPelsPerMeter = iis.readInt();
        long colorsUsed = iis.readUnsignedInt();
        long colorsImportant = iis.readUnsignedInt();
        metadata.compression = (int) compression;
        metadata.imageSize = (int) imageSize;
        metadata.xPixelsPerMeter = (int) xPelsPerMeter;
        metadata.yPixelsPerMeter = (int) yPelsPerMeter;
        metadata.colorsUsed = (int) colorsUsed;
        metadata.colorsImportant = (int) colorsImportant;
        if (size == 40) {
            // Windows 3.x and Windows NT
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    metadata.bmpVersion = VERSION_3;
                    imageType = VERSION_3_XP_EMBEDDED;
                    break;
                // No compression
                case BI_RGB:
                // 8-bit RLE compression
                case BI_RLE8:
                case // 4-bit RLE compression
                BI_RLE4:
                    // Read in the palette
                    int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
                    int sizeOfPalette = numberOfEntries * 4;
                    palette = new byte[sizeOfPalette];
                    iis.readFully(palette, 0, sizeOfPalette);
                    metadata.palette = palette;
                    metadata.paletteSize = numberOfEntries;
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_3_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_3_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_3_8_BIT;
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_3_24_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                        redMask = 0x7C00;
                        greenMask = 0x3E0;
                        // 0x1F;
                        blueMask = (1 << 5) - 1;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                        redMask = 0x00FF0000;
                        greenMask = 0x0000FF00;
                        blueMask = 0x000000FF;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    }
                    metadata.bmpVersion = VERSION_3;
                    break;
                case BI_BITFIELDS:
                    if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                    }
                    // BitsField encoding
                    redMask = (int) iis.readUnsignedInt();
                    greenMask = (int) iis.readUnsignedInt();
                    blueMask = (int) iis.readUnsignedInt();
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    if (colorsUsed != 0) {
                        // there is a palette
                        sizeOfPalette = (int) colorsUsed * 4;
                        palette = new byte[sizeOfPalette];
                        iis.readFully(palette, 0, sizeOfPalette);
                        metadata.palette = palette;
                        metadata.paletteSize = (int) colorsUsed;
                    }
                    metadata.bmpVersion = VERSION_3_NT;
                    break;
                default:
                    throw new RuntimeException(I18N.getString("BMPImageReader2"));
            }
        } else if (size == 108 || size == 124) {
            // Windows 4.x BMP
            if (size == 108)
                metadata.bmpVersion = VERSION_4;
            else if (size == 124)
                metadata.bmpVersion = VERSION_5;
            // rgb masks, valid only if comp is BI_BITFIELDS
            redMask = (int) iis.readUnsignedInt();
            greenMask = (int) iis.readUnsignedInt();
            blueMask = (int) iis.readUnsignedInt();
            // Only supported for 32bpp BI_RGB argb
            alphaMask = (int) iis.readUnsignedInt();
            long csType = iis.readUnsignedInt();
            int redX = iis.readInt();
            int redY = iis.readInt();
            int redZ = iis.readInt();
            int greenX = iis.readInt();
            int greenY = iis.readInt();
            int greenZ = iis.readInt();
            int blueX = iis.readInt();
            int blueY = iis.readInt();
            int blueZ = iis.readInt();
            long gammaRed = iis.readUnsignedInt();
            long gammaGreen = iis.readUnsignedInt();
            long gammaBlue = iis.readUnsignedInt();
            if (size == 124) {
                metadata.intent = iis.readInt();
                profileData = iis.readInt();
                profileSize = iis.readInt();
                iis.skipBytes(4);
            }
            metadata.colorSpace = (int) csType;
            if (csType == LCS_CALIBRATED_RGB) {
                // All the new fields are valid only for this case
                metadata.redX = redX;
                metadata.redY = redY;
                metadata.redZ = redZ;
                metadata.greenX = greenX;
                metadata.greenY = greenY;
                metadata.greenZ = greenZ;
                metadata.blueX = blueX;
                metadata.blueY = blueY;
                metadata.blueZ = blueZ;
                metadata.gammaRed = (int) gammaRed;
                metadata.gammaGreen = (int) gammaGreen;
                metadata.gammaBlue = (int) gammaBlue;
            }
            // Read in the palette
            int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
            int sizeOfPalette = numberOfEntries * 4;
            palette = new byte[sizeOfPalette];
            iis.readFully(palette, 0, sizeOfPalette);
            metadata.palette = palette;
            metadata.paletteSize = numberOfEntries;
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    if (size == 108) {
                        imageType = VERSION_4_XP_EMBEDDED;
                    } else if (size == 124) {
                        imageType = VERSION_5_XP_EMBEDDED;
                    }
                    break;
                default:
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_4_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_4_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_4_8_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_4_16_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x7C00;
                            greenMask = 0x3E0;
                            blueMask = 0x1F;
                        }
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_4_24_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_4_32_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x00FF0000;
                            greenMask = 0x0000FF00;
                            blueMask = 0x000000FF;
                        }
                    }
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    metadata.alphaMask = alphaMask;
            }
        } else {
            throw new RuntimeException(I18N.getString("BMPImageReader3"));
        }
    }
    if (height > 0) {
        // bottom up image
        isBottomUp = true;
    } else {
        // top down image
        isBottomUp = false;
        height = Math.abs(height);
    }
    // Reset Image Layout so there's only one tile.
    //Define the color space
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    if (metadata.colorSpace == PROFILE_LINKED || metadata.colorSpace == PROFILE_EMBEDDED) {
        iis.mark();
        iis.skipBytes(profileData - size);
        byte[] profile = new byte[profileSize];
        iis.readFully(profile, 0, profileSize);
        iis.reset();
        try {
            if (metadata.colorSpace == PROFILE_LINKED)
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(new String(profile)));
            else
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(profile));
        } catch (Exception e) {
            colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        }
    }
    if (bitsPerPixel == 0 || compression == BI_JPEG || compression == BI_PNG) {
        // the colorModel and sampleModel will be initialzed
        // by the  reader of embedded image
        colorModel = null;
        sampleModel = null;
    } else if (bitsPerPixel == 1 || bitsPerPixel == 4 || bitsPerPixel == 8) {
        // When number of bitsPerPixel is <= 8, we use IndexColorModel.
        numBands = 1;
        if (bitsPerPixel == 8) {
            int[] bandOffsets = new int[numBands];
            for (int i = 0; i < numBands; i++) {
                bandOffsets[i] = numBands - 1 - i;
            }
            sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        } else {
            // 1 and 4 bit pixels can be stored in a packed format.
            sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitsPerPixel);
        }
        // Create IndexColorModel from the palette.
        byte r[], g[], b[];
        if (imageType == VERSION_2_1_BIT || imageType == VERSION_2_4_BIT || imageType == VERSION_2_8_BIT) {
            size = palette.length / 3;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < (int) size; i++) {
                off = 3 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        } else {
            size = palette.length / 4;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < size; i++) {
                off = 4 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        }
        if (ImageUtil.isIndicesForGrayscale(r, g, b))
            colorModel = ImageUtil.createColorModel(null, sampleModel);
        else
            colorModel = new IndexColorModel(bitsPerPixel, (int) size, r, g, b);
    } else if (bitsPerPixel == 16) {
        numBands = 3;
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_USHORT, width, height, new int[] { redMask, greenMask, blueMask });
        colorModel = new DirectColorModel(colorSpace, 16, redMask, greenMask, blueMask, 0, false, DataBuffer.TYPE_USHORT);
    } else if (bitsPerPixel == 32) {
        numBands = alphaMask == 0 ? 3 : 4;
        if (redMask == 0 || greenMask == 0 || blueMask == 0) {
            redMask = 0xFF0000;
            greenMask = 0xFF00;
            blueMask = 0xFF;
            alphaMask = 0xFF000000;
        }
        // The number of bands in the SampleModel is determined by
        // the length of the mask array passed in.
        int[] bitMasks = numBands == 3 ? new int[] { redMask, greenMask, blueMask } : new int[] { redMask, greenMask, blueMask, alphaMask };
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, bitMasks);
        colorModel = new DirectColorModel(colorSpace, 32, redMask, greenMask, blueMask, alphaMask, false, DataBuffer.TYPE_INT);
    } else {
        numBands = 3;
        // Create SampleModel
        int[] bandOffsets = new int[numBands];
        for (int i = 0; i < numBands; i++) {
            bandOffsets[i] = numBands - 1 - i;
        }
        sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        colorModel = ImageUtil.createColorModel(colorSpace, sampleModel);
    }
    originalSampleModel = sampleModel;
    originalColorModel = colorModel;
    // Reset to the start of bitmap; then jump to the
    //start of image data
    iis.reset();
    iis.skipBytes(bitmapOffset);
    gotHeader = true;
    // Store the stream position where the image data starts
    imageDataOffset = iis.getStreamPosition();
}
Example 32
Project: clj-pdf-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 33
Project: folio100_frameworks_base-master  File: ColorConvertOp.java View source code
/**
         * For the full ICC case.
         * 
         * @param src
         *            the src.
         * @param dst
         *            the dst.
         * @param convSeq
         *            the conv seq.
         * @return the transform.
         */
public ICC_Transform getTransform(ICC_Profile src, ICC_Profile dst, ICC_Profile convSeq[]) {
    if (transform != null && src == transform.getSrc() && dst == transform.getDst()) {
        return transform;
    }
    int length = convSeq.length;
    int srcFlg = 0, dstFlg = 0;
    if (length == 0 || src != convSeq[0]) {
        if (src != null) {
            // need src profile
            srcFlg = 1;
        }
    }
    if (length == 0 || dst != convSeq[length - 1]) {
        if (dst != null) {
            // need dst profile
            dstFlg = 1;
        }
    }
    ICC_Profile profiles[];
    int nProfiles = length + srcFlg + dstFlg;
    if (nProfiles == length) {
        profiles = convSeq;
    } else {
        profiles = new ICC_Profile[nProfiles];
        int pos = 0;
        if (srcFlg != 0) {
            profiles[pos++] = src;
        }
        for (int i = 0; i < length; i++) {
            profiles[pos++] = convSeq[i];
        }
        if (dstFlg != 0) {
            profiles[pos++] = dst;
        }
    }
    return transform = new ICC_Transform(profiles);
}
Example 34
Project: iText-4.2.0-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 35
Project: itext-as-in-free-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 36
Project: itext-forked-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 37
Project: itext2-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 38
Project: open-mika-master  File: ColorScaler.java View source code
/**
     * Use this method only for double of float transfer types.
     * Extracts scaling data from the color space signature
     * and other tags, stored in the profile
     * @param pf - ICC profile
     */
public void loadScalingData(ICC_Profile pf) {
    // Supposing double or float transfer type
    isTTypeIntegral = false;
    nColorChannels = pf.getNumComponents();
    // Get min/max values directly from the profile
    // Very much like fillMinMaxValues in ICC_ColorSpace
    float maxValues[] = new float[nColorChannels];
    float minValues[] = new float[nColorChannels];
    switch(pf.getColorSpaceType()) {
        case ColorSpace.TYPE_XYZ:
            minValues[0] = 0;
            minValues[1] = 0;
            minValues[2] = 0;
            maxValues[0] = MAX_XYZ;
            maxValues[1] = MAX_XYZ;
            maxValues[2] = MAX_XYZ;
            break;
        case ColorSpace.TYPE_Lab:
            minValues[0] = 0;
            minValues[1] = -128;
            minValues[2] = -128;
            maxValues[0] = 100;
            maxValues[1] = 127;
            maxValues[2] = 127;
            break;
        default:
            for (int i = 0; i < nColorChannels; i++) {
                minValues[i] = 0;
                maxValues[i] = 1;
            }
    }
    channelMinValues = minValues;
    channelMulipliers = new float[nColorChannels];
    invChannelMulipliers = new float[nColorChannels];
    for (int i = 0; i < nColorChannels; i++) {
        channelMulipliers[i] = MAX_SHORT / (maxValues[i] - channelMinValues[i]);
        invChannelMulipliers[i] = (maxValues[i] - channelMinValues[i]) / MAX_SHORT;
    }
}
Example 39
Project: pades_signing_2.1.5-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 40
Project: PDF-to-unusual-HTML-master  File: PDICCBased.java View source code
/**
     * 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.
     */
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);
    } finally {
        if (profile != null) {
            profile.close();
        }
    }
    return cSpace;
}
Example 41
Project: poreid-master  File: FileFormatReader.java View source code
/** Read the color specifications.
     */
public void readColourSpecificationBox(int length) throws IOException {
    // read METHOD field
    byte method = (byte) in.readByte();
    // read PREC field
    byte prec = (byte) in.readByte();
    // read APPROX field
    byte approx = (byte) in.readByte();
    if (method == 2) {
        byte[] data = new byte[length - 3];
        in.readFully(data, 0, data.length);
        profile = ICC_Profile.getInstance(data);
    } else
        // read EnumCS field
        colorSpaceType = in.readInt();
    if (metadata != null) {
        metadata.addNode(new ColorSpecificationBox(method, prec, approx, colorSpaceType, profile));
    }
}
Example 42
Project: ptii-master  File: DoubleMatrixToJAI.java View source code
/** Fire this actor.
     *  Output the JAIImageToken constructed from the matrix of doubles.
     *  @exception IllegalActionException If a contained method throws it,
     *   or if a token is received that contains a null image.
     */
public void fire() throws IllegalActionException {
    super.fire();
    DoubleMatrixToken doubleMatrixToken = (DoubleMatrixToken) input.get(0);
    double[][] data = doubleMatrixToken.doubleMatrix();
    int width = doubleMatrixToken.getRowCount();
    int height = doubleMatrixToken.getColumnCount();
    double[] newData = new double[width * height];
    _maxValue = 1;
    _minValue = 0;
    if (_scale) {
        switch(_dataFormat) {
            case _BYTE:
                _maxValue = (double) Byte.MAX_VALUE - (double) Byte.MIN_VALUE;
                _minValue = 0;
                break;
            case _INT:
                _maxValue = Integer.MAX_VALUE;
                _minValue = Integer.MIN_VALUE;
                break;
            case _SHORT:
                _maxValue = Short.MAX_VALUE;
                _minValue = Short.MIN_VALUE;
                break;
            case _USHORT:
                _maxValue = (double) Short.MAX_VALUE - (double) Short.MIN_VALUE;
                _minValue = 0;
                break;
            case _FLOAT:
                _maxValue = Float.MAX_VALUE;
                break;
            case _DOUBLE:
                _maxValue = Double.MAX_VALUE;
                break;
            default:
                throw new InternalErrorException(this, null, "Invalid value for _dataFormat private variable. " + "DoubleMatrixToJAI actor (" + getFullName() + ") on data type " + _dataFormat);
        }
        if ((_dataFormat == _DOUBLE) || (_dataFormat == _FLOAT)) {
            System.out.println("DoubleMatrixTOJAI:0");
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    // There is some confusion about which order the
                    // array should be in.
                    // We go with i*height + j here so that we
                    // can read in data from the SDF VQ actors.
                    //                         newData[i*height + j] = data[i][j];
                    //                         newData[i*height + j] = newData[i*height + j] - 0.5D;
                    //                         newData[i*height + j] = newData[i*height + j]*2;
                    //                         newData[i*height + j] = newData[i*height + j]*_maxValue;
                    newData[i + (j * width)] = data[i][j];
                    newData[i + (j * width)] = newData[i + (j * width)] - 0.5D;
                    newData[i + (j * width)] = newData[i + (j * width)] * 2;
                    newData[i + (j * width)] = newData[i + (j * width)] * _maxValue;
                }
            }
        } else {
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    //                         newData[i*height + j] =
                    //                             data[i][j]*(_maxValue - _minValue) + _minValue;
                    newData[i + (j * width)] = (data[i][j] * (_maxValue - _minValue)) + _minValue;
                }
            }
        }
    } else {
        // Convert the matrix of doubles into an array of doubles
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                //                    newData[i*height + j] = data[i][j];
                newData[i + (j * width)] = data[i][j];
            }
        }
    }
    // Create a new dataBuffer from the array of doubles
    DataBufferDouble dataBuffer = new DataBufferDouble(newData, width * height);
    // The length of the bandOffset array indicates how many bands
    // there are.  Since we are just dealing with a single
    // DoubleMatrixToken, the length of this array will be one.
    // The values of the array indicate the offset to be added
    // To the bands.  This is set to 0.
    int[] bandOffset = new int[1];
    bandOffset[0] = 0;
    // Create a ComponentSampleModel, with type double, the same width
    // and height as the matrix, a pixel stride of one (the final image
    // is single-banded), and a scanline stride equal to the width.
    ComponentSampleModelJAI sampleModel = new ComponentSampleModelJAI(DataBuffer.TYPE_DOUBLE, width, height, 1, width, bandOffset);
    // Create a new raster that has its origin at (0, 0).
    Raster raster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point());
    // Create a grayscale colormodel.
    ComponentColorModel colorModel = new ComponentColorModel(new ICC_ColorSpace(ICC_Profile.getInstance(ColorSpace.CS_GRAY)), false, false, Transparency.OPAQUE, DataBuffer.TYPE_DOUBLE);
    TiledImage tiledImage = new TiledImage(0, 0, width, height, 0, 0, sampleModel, colorModel);
    tiledImage.setData(raster);
    ParameterBlock parameters = new ParameterBlock();
    parameters.addSource(tiledImage);
    switch(_dataFormat) {
        case _BYTE:
            parameters.add(DataBuffer.TYPE_BYTE);
            break;
        case _DOUBLE:
            parameters.add(DataBuffer.TYPE_DOUBLE);
            break;
        case _FLOAT:
            parameters.add(DataBuffer.TYPE_FLOAT);
            break;
        case _INT:
            parameters.add(DataBuffer.TYPE_INT);
            break;
        case _SHORT:
            parameters.add(DataBuffer.TYPE_SHORT);
            break;
        case _USHORT:
            parameters.add(DataBuffer.TYPE_USHORT);
            break;
        default:
            throw new InternalErrorException(this, null, "Invalid value for _dataFormat private variable. " + "DoubleMatrixToJAI actor (" + getFullName() + ") on data type " + _dataFormat);
    }
    RenderedOp newImage = JAI.create("format", parameters);
    output.send(0, new JAIImageToken(newImage));
}
Example 43
Project: sysart-itext-master  File: PdfWriter.java View source code
//  [C11] Output intents
/**
     * Sets the values of the output intent dictionary. Null values are allowed to
     * suppress any key.
     *
     * @param outputConditionIdentifier a value
     * @param outputCondition           a value, "PDFA/A" to force GTS_PDFA1, otherwise cued by pdfxConformance.
     * @param registryName              a value
     * @param info                      a value
     * @param colorProfile              a value
     * @since 2.1.5
     * @throws IOException on error
     */
public void setOutputIntents(String outputConditionIdentifier, String outputCondition, String registryName, String info, ICC_Profile colorProfile) throws IOException {
    getExtraCatalog();
    PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
    if (outputCondition != null)
        out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
    if (outputConditionIdentifier != null)
        out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
    if (registryName != null)
        out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
    if (info != null)
        out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
    if (colorProfile != null) {
        PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
        out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
    }
    PdfName intentSubtype;
    if (pdfxConformance.isPdfA1() || "PDFA/1".equals(outputCondition)) {
        intentSubtype = PdfName.GTS_PDFA1;
    } else {
        intentSubtype = PdfName.GTS_PDFX;
    }
    out.put(PdfName.S, intentSubtype);
    extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
Example 44
Project: with-aes-master  File: CatalogValidationHelper.java View source code
/**
	 * This method checks the destOutputProfile which must be a valid ICCProfile.
	 * 
	 * If an other ICCProfile exists in the mapDestOutputProfile, a
	 * ValdiationError (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE) is
	 * returned because of only one profile is authorized. If the ICCProfile
	 * already exist in the mapDestOutputProfile, the method returns null. If the
	 * destOutputProfile contains an invalid ICCProfile, a ValidationError
	 * (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID) is returned If the
	 * destOutputProfile is an empty stream, a
	 * ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY) is returned.
	 * 
	 * If the destOutputFile is valid, mapDestOutputProfile is updated, the
	 * ICCProfile is added to the document handler and null is returned.
	 * 
	 * @param destOutputProfile
	 * @param cDoc
	 * @param tmpDestOutputProfile
	 * @param handler
	 * @return
	 * @throws ValidationException
	 */
protected ValidationError validateICCProfile(COSBase destOutputProfile, COSDocument cDoc, Map<COSObjectKey, Boolean> mapDestOutputProfile, DocumentHandler handler) throws ValidationException {
    try {
        if (destOutputProfile == null) {
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object");
        }
        // this is a object reference
        if (destOutputProfile instanceof COSObject) {
            if (mapDestOutputProfile.containsKey(new COSObjectKey((COSObject) destOutputProfile))) {
                // ---- the profile is already checked. continue
                return null;
            } else if (!mapDestOutputProfile.isEmpty()) {
                // ---- A DestOutputProfile exits but it isn't the same, error
                return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE, "More than one ICCProfile is defined");
            }
        // else  the profile will be kept in the tmpDestOutputProfile if it is valid
        }
        PDStream stream = PDStream.createFromCOS(COSUtils.getAsStream(destOutputProfile, cDoc));
        if (stream == null) {
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object");
        }
        ICC_Profile iccp = ICC_Profile.getInstance(stream.getByteArray());
        // check the ICC Profile version (6.2.2)
        if (iccp.getMajorVersion() == 2) {
            if (iccp.getMinorVersion() > 0x40) {
                // The current profile version number is "2.4.0" (encoded as 02400000h"
                return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
            // else OK
            }
        } else if (iccp.getMajorVersion() > 2) {
            // The current profile version number is "2.4.0" (encoded as 02400000h"
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
        }
        if (handler.getIccProfileWrapper() == null) {
            handler.setIccProfileWrapper(new ICCProfileWrapper(iccp));
        }
        // ---- keep reference to avoid multiple profile definition
        mapDestOutputProfile.put(new COSObjectKey((COSObject) destOutputProfile), true);
    } catch (IllegalArgumentException e) {
        return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "DestOutputProfile isn't a ICCProfile");
    } catch (IOException e) {
        throw new ValidationException("Unable to parse the ICC Profile", e);
    }
    return null;
}
Example 45
Project: WS171-frameworks-base-master  File: ColorConvertOp.java View source code
/**
         * For the full ICC case.
         * 
         * @param src
         *            the src.
         * @param dst
         *            the dst.
         * @param convSeq
         *            the conv seq.
         * @return the transform.
         */
public ICC_Transform getTransform(ICC_Profile src, ICC_Profile dst, ICC_Profile convSeq[]) {
    if (transform != null && src == transform.getSrc() && dst == transform.getDst()) {
        return transform;
    }
    int length = convSeq.length;
    int srcFlg = 0, dstFlg = 0;
    if (length == 0 || src != convSeq[0]) {
        if (src != null) {
            // need src profile
            srcFlg = 1;
        }
    }
    if (length == 0 || dst != convSeq[length - 1]) {
        if (dst != null) {
            // need dst profile
            dstFlg = 1;
        }
    }
    ICC_Profile profiles[];
    int nProfiles = length + srcFlg + dstFlg;
    if (nProfiles == length) {
        profiles = convSeq;
    } else {
        profiles = new ICC_Profile[nProfiles];
        int pos = 0;
        if (srcFlg != 0) {
            profiles[pos++] = src;
        }
        for (int i = 0; i < length; i++) {
            profiles[pos++] = convSeq[i];
        }
        if (dstFlg != 0) {
            profiles[pos++] = dst;
        }
    }
    return transform = new ICC_Transform(profiles);
}
Example 46
Project: classlib6-master  File: BMPImageReader.java View source code
public void readHeader() throws IOException {
    if (gotHeader)
        return;
    if (iis == null) {
        throw new IllegalStateException("Input source not set!");
    }
    int profileData = 0, profileSize = 0;
    this.metadata = new BMPMetadata();
    iis.mark();
    // read and check the magic marker
    byte[] marker = new byte[2];
    iis.read(marker);
    if (marker[0] != 0x42 || marker[1] != 0x4d)
        throw new IllegalArgumentException(I18N.getString("BMPImageReader1"));
    // Read file size
    bitmapFileSize = iis.readUnsignedInt();
    // skip the two reserved fields
    iis.skipBytes(4);
    // Offset to the bitmap from the beginning
    bitmapOffset = iis.readUnsignedInt();
    // End File Header
    // Start BitmapCoreHeader
    long size = iis.readUnsignedInt();
    if (size == 12) {
        width = iis.readShort();
        height = iis.readShort();
    } else {
        width = iis.readInt();
        height = iis.readInt();
    }
    metadata.width = width;
    metadata.height = height;
    int planes = iis.readUnsignedShort();
    bitsPerPixel = iis.readUnsignedShort();
    //metadata.colorPlane = planes;
    metadata.bitsPerPixel = (short) bitsPerPixel;
    // As BMP always has 3 rgb bands, except for Version 5,
    // which is bgra
    numBands = 3;
    if (size == 12) {
        // Windows 2.x and OS/2 1.x
        metadata.bmpVersion = VERSION_2;
        // Classify the image type
        if (bitsPerPixel == 1) {
            imageType = VERSION_2_1_BIT;
        } else if (bitsPerPixel == 4) {
            imageType = VERSION_2_4_BIT;
        } else if (bitsPerPixel == 8) {
            imageType = VERSION_2_8_BIT;
        } else if (bitsPerPixel == 24) {
            imageType = VERSION_2_24_BIT;
        }
        // Read in the palette
        int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 3);
        int sizeOfPalette = numberOfEntries * 3;
        palette = new byte[sizeOfPalette];
        iis.readFully(palette, 0, sizeOfPalette);
        metadata.palette = palette;
        metadata.paletteSize = numberOfEntries;
    } else {
        compression = iis.readUnsignedInt();
        imageSize = iis.readUnsignedInt();
        long xPelsPerMeter = iis.readInt();
        long yPelsPerMeter = iis.readInt();
        long colorsUsed = iis.readUnsignedInt();
        long colorsImportant = iis.readUnsignedInt();
        metadata.compression = (int) compression;
        metadata.xPixelsPerMeter = (int) xPelsPerMeter;
        metadata.yPixelsPerMeter = (int) yPelsPerMeter;
        metadata.colorsUsed = (int) colorsUsed;
        metadata.colorsImportant = (int) colorsImportant;
        if (size == 40) {
            // Windows 3.x and Windows NT
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    metadata.bmpVersion = VERSION_3;
                    imageType = VERSION_3_XP_EMBEDDED;
                    break;
                // No compression
                case BI_RGB:
                // 8-bit RLE compression
                case BI_RLE8:
                case // 4-bit RLE compression
                BI_RLE4:
                    // Read in the palette
                    int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
                    int sizeOfPalette = numberOfEntries * 4;
                    palette = new byte[sizeOfPalette];
                    iis.readFully(palette, 0, sizeOfPalette);
                    metadata.palette = palette;
                    metadata.paletteSize = numberOfEntries;
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_3_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_3_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_3_8_BIT;
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_3_24_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                        redMask = 0x7C00;
                        greenMask = 0x3E0;
                        // 0x1F;
                        blueMask = (1 << 5) - 1;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                        redMask = 0x00FF0000;
                        greenMask = 0x0000FF00;
                        blueMask = 0x000000FF;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    }
                    metadata.bmpVersion = VERSION_3;
                    break;
                case BI_BITFIELDS:
                    if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                    }
                    // BitsField encoding
                    redMask = (int) iis.readUnsignedInt();
                    greenMask = (int) iis.readUnsignedInt();
                    blueMask = (int) iis.readUnsignedInt();
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    if (colorsUsed != 0) {
                        // there is a palette
                        sizeOfPalette = (int) colorsUsed * 4;
                        palette = new byte[sizeOfPalette];
                        iis.readFully(palette, 0, sizeOfPalette);
                        metadata.palette = palette;
                        metadata.paletteSize = (int) colorsUsed;
                    }
                    metadata.bmpVersion = VERSION_3_NT;
                    break;
                default:
                    throw new RuntimeException(I18N.getString("BMPImageReader2"));
            }
        } else if (size == 108 || size == 124) {
            // Windows 4.x BMP
            if (size == 108)
                metadata.bmpVersion = VERSION_4;
            else if (size == 124)
                metadata.bmpVersion = VERSION_5;
            // rgb masks, valid only if comp is BI_BITFIELDS
            redMask = (int) iis.readUnsignedInt();
            greenMask = (int) iis.readUnsignedInt();
            blueMask = (int) iis.readUnsignedInt();
            // Only supported for 32bpp BI_RGB argb
            alphaMask = (int) iis.readUnsignedInt();
            long csType = iis.readUnsignedInt();
            int redX = iis.readInt();
            int redY = iis.readInt();
            int redZ = iis.readInt();
            int greenX = iis.readInt();
            int greenY = iis.readInt();
            int greenZ = iis.readInt();
            int blueX = iis.readInt();
            int blueY = iis.readInt();
            int blueZ = iis.readInt();
            long gammaRed = iis.readUnsignedInt();
            long gammaGreen = iis.readUnsignedInt();
            long gammaBlue = iis.readUnsignedInt();
            if (size == 124) {
                metadata.intent = iis.readInt();
                profileData = iis.readInt();
                profileSize = iis.readInt();
                iis.skipBytes(4);
            }
            metadata.colorSpace = (int) csType;
            if (csType == LCS_CALIBRATED_RGB) {
                // All the new fields are valid only for this case
                metadata.redX = redX;
                metadata.redY = redY;
                metadata.redZ = redZ;
                metadata.greenX = greenX;
                metadata.greenY = greenY;
                metadata.greenZ = greenZ;
                metadata.blueX = blueX;
                metadata.blueY = blueY;
                metadata.blueZ = blueZ;
                metadata.gammaRed = (int) gammaRed;
                metadata.gammaGreen = (int) gammaGreen;
                metadata.gammaBlue = (int) gammaBlue;
            }
            // Read in the palette
            int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
            int sizeOfPalette = numberOfEntries * 4;
            palette = new byte[sizeOfPalette];
            iis.readFully(palette, 0, sizeOfPalette);
            metadata.palette = palette;
            metadata.paletteSize = numberOfEntries;
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    if (size == 108) {
                        imageType = VERSION_4_XP_EMBEDDED;
                    } else if (size == 124) {
                        imageType = VERSION_5_XP_EMBEDDED;
                    }
                    break;
                default:
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_4_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_4_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_4_8_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_4_16_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x7C00;
                            greenMask = 0x3E0;
                            blueMask = 0x1F;
                        }
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_4_24_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_4_32_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x00FF0000;
                            greenMask = 0x0000FF00;
                            blueMask = 0x000000FF;
                        }
                    }
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    metadata.alphaMask = alphaMask;
            }
        } else {
            throw new RuntimeException(I18N.getString("BMPImageReader3"));
        }
    }
    if (height > 0) {
        // bottom up image
        isBottomUp = true;
    } else {
        // top down image
        isBottomUp = false;
        height = Math.abs(height);
    }
    // Reset Image Layout so there's only one tile.
    //Define the color space
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    if (metadata.colorSpace == PROFILE_LINKED || metadata.colorSpace == PROFILE_EMBEDDED) {
        iis.mark();
        iis.skipBytes(profileData - size);
        byte[] profile = new byte[profileSize];
        iis.readFully(profile, 0, profileSize);
        iis.reset();
        try {
            if (metadata.colorSpace == PROFILE_LINKED && isLinkedProfileAllowed() && !isUncOrDevicePath(profile)) {
                String path = new String(profile, "windows-1252");
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(path));
            } else {
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(profile));
            }
        } catch (Exception e) {
            colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        }
    }
    if (bitsPerPixel == 0 || compression == BI_JPEG || compression == BI_PNG) {
        // the colorModel and sampleModel will be initialzed
        // by the  reader of embedded image
        colorModel = null;
        sampleModel = null;
    } else if (bitsPerPixel == 1 || bitsPerPixel == 4 || bitsPerPixel == 8) {
        // When number of bitsPerPixel is <= 8, we use IndexColorModel.
        numBands = 1;
        if (bitsPerPixel == 8) {
            int[] bandOffsets = new int[numBands];
            for (int i = 0; i < numBands; i++) {
                bandOffsets[i] = numBands - 1 - i;
            }
            sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        } else {
            // 1 and 4 bit pixels can be stored in a packed format.
            sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitsPerPixel);
        }
        // Create IndexColorModel from the palette.
        byte r[], g[], b[];
        if (imageType == VERSION_2_1_BIT || imageType == VERSION_2_4_BIT || imageType == VERSION_2_8_BIT) {
            size = palette.length / 3;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < (int) size; i++) {
                off = 3 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        } else {
            size = palette.length / 4;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < size; i++) {
                off = 4 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        }
        if (ImageUtil.isIndicesForGrayscale(r, g, b))
            colorModel = ImageUtil.createColorModel(null, sampleModel);
        else
            colorModel = new IndexColorModel(bitsPerPixel, (int) size, r, g, b);
    } else if (bitsPerPixel == 16) {
        numBands = 3;
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_USHORT, width, height, new int[] { redMask, greenMask, blueMask });
        colorModel = new DirectColorModel(colorSpace, 16, redMask, greenMask, blueMask, 0, false, DataBuffer.TYPE_USHORT);
    } else if (bitsPerPixel == 32) {
        numBands = alphaMask == 0 ? 3 : 4;
        // The number of bands in the SampleModel is determined by
        // the length of the mask array passed in.
        int[] bitMasks = numBands == 3 ? new int[] { redMask, greenMask, blueMask } : new int[] { redMask, greenMask, blueMask, alphaMask };
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, bitMasks);
        colorModel = new DirectColorModel(colorSpace, 32, redMask, greenMask, blueMask, alphaMask, false, DataBuffer.TYPE_INT);
    } else {
        numBands = 3;
        // Create SampleModel
        int[] bandOffsets = new int[numBands];
        for (int i = 0; i < numBands; i++) {
            bandOffsets[i] = numBands - 1 - i;
        }
        sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        colorModel = ImageUtil.createColorModel(colorSpace, sampleModel);
    }
    originalSampleModel = sampleModel;
    originalColorModel = colorModel;
    // Reset to the start of bitmap; then jump to the
    //start of image data
    iis.reset();
    iis.skipBytes(bitmapOffset);
    gotHeader = true;
}
Example 47
Project: JamVM-PH-master  File: ProfileHeader.java View source code
/**
   * Creates a header, setting the header file size at the same time.
   * @param size the profile file size.
   */
public byte[] getData(int size) {
    byte[] data = new byte[HEADERSIZE];
    ByteBuffer buf = ByteBuffer.wrap(data);
    buf.putInt(ICC_Profile.icHdrSize, size);
    buf.putInt(ICC_Profile.icHdrCmmId, cmmId);
    buf.putShort(ICC_Profile.icHdrVersion, (short) (majorVersion << 8 | minorVersion));
    for (int i = 1; i < classMap.length; i += 2) if (profileClass == classMap[i])
        buf.putInt(ICC_Profile.icHdrDeviceClass, classMap[i - 1]);
    for (int i = 1; i < csTypeMap.length; i += 2) if (csTypeMap[i] == colorSpace)
        buf.putInt(ICC_Profile.icHdrColorSpace, csTypeMap[i - 1]);
    for (int i = 1; i < csTypeMap.length; i += 2) if (csTypeMap[i] == profileColorSpace)
        buf.putInt(ICC_Profile.icHdrPcs, csTypeMap[i - 1]);
    System.arraycopy(timestamp, 0, data, ICC_Profile.icHdrDate, timestamp.length);
    buf.putInt(ICC_Profile.icHdrMagic, icMagicNumber);
    buf.putInt(ICC_Profile.icHdrPlatform, platform);
    buf.putInt(ICC_Profile.icHdrFlags, flags);
    buf.putInt(ICC_Profile.icHdrManufacturer, manufacturerSig);
    buf.putInt(ICC_Profile.icHdrModel, modelSig);
    System.arraycopy(attributes, 0, data, ICC_Profile.icHdrAttributes, attributes.length);
    buf.putInt(ICC_Profile.icHdrRenderingIntent, intent);
    System.arraycopy(illuminant, 0, data, ICC_Profile.icHdrIlluminant, illuminant.length);
    buf.putInt(ICC_Profile.icHdrCreator, creatorSig);
    return buf.array();
}
Example 48
Project: padaf-master  File: CatalogValidationHelper.java View source code
/**
   * This method checks the destOutputProfile which must be a valid ICCProfile.
   * 
   * If an other ICCProfile exists in the mapDestOutputProfile, a
   * ValdiationError (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE) is
   * returned because of only one profile is authorized. If the ICCProfile
   * already exist in the mapDestOutputProfile, the method returns null. If the
   * destOutputProfile contains an invalid ICCProfile, a ValidationError
   * (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID) is returned If the
   * destOutputProfile is an empty stream, a
   * ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY) is returned.
   * 
   * If the destOutputFile is valid, mapDestOutputProfile is updated, the
   * ICCProfile is added to the document handler and null is returned.
   * 
   * @param destOutputProfile
   * @param cDoc
   * @param tmpDestOutputProfile
   * @param handler
   * @return
   * @throws ValidationException
   */
protected ValidationError validateICCProfile(COSBase destOutputProfile, COSDocument cDoc, Map<COSObjectKey, Boolean> mapDestOutputProfile, DocumentHandler handler) throws ValidationException {
    try {
        if (destOutputProfile == null) {
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object");
        }
        // this is a object reference
        if (destOutputProfile instanceof COSObject) {
            if (mapDestOutputProfile.containsKey(new COSObjectKey((COSObject) destOutputProfile))) {
                // ---- the profile is already checked. continue
                return null;
            } else if (!mapDestOutputProfile.isEmpty()) {
                // ---- A DestOutputProfile exits but it isn't the same, error
                return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE, "More than one ICCProfile is defined");
            }
        // else  the profile will be kept in the tmpDestOutputProfile if it is valid
        }
        PDStream stream = PDStream.createFromCOS(COSUtils.getAsStream(destOutputProfile, cDoc));
        if (stream == null) {
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object");
        }
        ICC_Profile iccp = ICC_Profile.getInstance(stream.getByteArray());
        // check the ICC Profile version (6.2.2)
        if (iccp.getMajorVersion() == 2) {
            if (iccp.getMinorVersion() > 0x20) {
                // in PDF 1.4, max version is 02h.20h (meaning V 3.5)
                return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
            }
        // else OK
        } else if (iccp.getMajorVersion() > 2) {
            // in PDF 1.4, max version is 02h.20h (meaning V 3.5)
            return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
        }
        if (handler.getIccProfileWrapper() == null) {
            handler.setIccProfileWrapper(new ICCProfileWrapper(iccp));
        }
        // ---- keep reference to avoid multiple profile definition
        mapDestOutputProfile.put(new COSObjectKey((COSObject) destOutputProfile), true);
    } catch (IllegalArgumentException e) {
        return new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "DestOutputProfile isn't a ICCProfile");
    } catch (IOException e) {
        throw new ValidationException("Unable to parse the ICC Profile", e);
    }
    return null;
}
Example 49
Project: nuxeo-master  File: AbstractPictureAdapter.java View source code
protected void setMetadata() throws IOException {
    boolean imageInfoUsed = false;
    ImageInfo imageInfo = getImageInfo();
    if (imageInfo != null) {
        width = imageInfo.getWidth();
        height = imageInfo.getHeight();
        depth = imageInfo.getDepth();
        imageInfoUsed = true;
    }
    Map<String, Object> metadata = getImagingService().getImageMetadata(fileContent);
    description = (String) metadata.get(META_DESCRIPTION);
    if (!imageInfoUsed) {
        width = (Integer) metadata.get(META_WIDTH);
        height = (Integer) metadata.get(META_HEIGHT);
    }
    doc.setPropertyValue("picture:" + FIELD_BYLINE, (String) metadata.get(META_BY_LINE));
    doc.setPropertyValue("picture:" + FIELD_CAPTION, (String) metadata.get(META_CAPTION));
    doc.setPropertyValue("picture:" + FIELD_CREDIT, (String) metadata.get(META_CREDIT));
    if (metadata.containsKey(META_DATE_CREATED)) {
        doc.setPropertyValue("picture:" + FIELD_DATELINE, metadata.get(META_DATE_CREATED).toString());
    }
    doc.setPropertyValue("picture:" + FIELD_HEADLINE, (String) metadata.get(META_HEADLINE));
    doc.setPropertyValue("picture:" + FIELD_LANGUAGE, (String) metadata.get(META_LANGUAGE));
    doc.setPropertyValue("picture:" + FIELD_ORIGIN, (String) metadata.get(META_OBJECT_NAME));
    doc.setPropertyValue("picture:" + FIELD_SOURCE, (String) metadata.get(META_SOURCE));
    // Set EXIF info
    doc.setPropertyValue("imd:image_description", (String) metadata.get(META_DESCRIPTION));
    doc.setPropertyValue("imd:user_comment", (String) metadata.get(META_COMMENT));
    doc.setPropertyValue("imd:equipment", (String) metadata.get(META_EQUIPMENT));
    Date dateTimeOriginal = (Date) metadata.get(META_ORIGINALDATE);
    if (dateTimeOriginal != null) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dateTimeOriginal);
        doc.setPropertyValue("imd:date_time_original", calendar);
    }
    doc.setPropertyValue("imd:xresolution", (Integer) metadata.get(META_HRESOLUTION));
    doc.setPropertyValue("imd:yresolution", (Integer) metadata.get(META_VRESOLUTION));
    doc.setPropertyValue("imd:pixel_xdimension", (Integer) metadata.get(META_PIXEL_XDIMENSION));
    doc.setPropertyValue("imd:pixel_ydimension", (Integer) metadata.get(META_PIXEL_YDIMENSION));
    doc.setPropertyValue("imd:copyright", (String) metadata.get(META_COPYRIGHT));
    doc.setPropertyValue("imd:exposure_time", (String) metadata.get(META_EXPOSURE));
    doc.setPropertyValue("imd:iso_speed_ratings", (String) metadata.get(META_ISOSPEED));
    doc.setPropertyValue("imd:focal_length", (Double) metadata.get(META_FOCALLENGTH));
    doc.setPropertyValue("imd:color_space", (String) metadata.get(META_COLORSPACE));
    doc.setPropertyValue("imd:white_balance", (String) metadata.get(META_WHITEBALANCE));
    ICC_Profile iccProfile = (ICC_Profile) metadata.get(META_ICCPROFILE);
    if (iccProfile != null) {
        doc.setPropertyValue("imd:icc_profile", iccProfile.toString());
    }
    doc.setPropertyValue("imd:orientation", (String) metadata.get(META_ORIENTATION));
    doc.setPropertyValue("imd:fnumber", (Double) metadata.get(META_FNUMBER));
    // Set IPTC info
    doc.setPropertyValue("iptc:by_line", (String) metadata.get(META_BY_LINE));
    doc.setPropertyValue("iptc:by_line_title", (String) metadata.get(META_BY_LINE_TITLE));
    doc.setPropertyValue("iptc:caption", (String) metadata.get(META_CAPTION));
    doc.setPropertyValue("iptc:category", (String) metadata.get(META_CATEGORY));
    doc.setPropertyValue("iptc:city", (String) metadata.get(META_CITY));
    doc.setPropertyValue("iptc:copyright_notice", (String) metadata.get(META_COPYRIGHT_NOTICE));
    doc.setPropertyValue("iptc:country_or_primary_location", (String) metadata.get(META_COUNTRY_OR_PRIMARY_LOCATION));
    doc.setPropertyValue("iptc:credit", (String) metadata.get(META_CREDIT));
    Date dateCreated = (Date) metadata.get(META_DATE_CREATED);
    if (dateCreated != null) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dateCreated);
        doc.setPropertyValue("iptc:date_created", calendar);
    }
    doc.setPropertyValue("iptc:headline", (String) metadata.get(META_HEADLINE));
    doc.setPropertyValue("iptc:keywords", (String) metadata.get(META_KEYWORDS));
    doc.setPropertyValue("iptc:language", (String) metadata.get(META_LANGUAGE));
    doc.setPropertyValue("iptc:object_name", (String) metadata.get(META_OBJECT_NAME));
    doc.setPropertyValue("iptc:original_transmission_ref", (String) metadata.get(META_ORIGINAL_TRANSMISSION_REFERENCE));
    doc.setPropertyValue("iptc:originating_program", (String) metadata.get(META_ORIGINATING_PROGRAM));
    doc.setPropertyValue("iptc:province_or_state", (String) metadata.get(META_PROVINCE_OR_STATE));
    doc.setPropertyValue("iptc:record_version", (String) metadata.get(META_RECORD_VERSION));
    Date releaseDate = (Date) metadata.get(META_RELEASE_DATE);
    if (releaseDate != null) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(releaseDate);
        doc.setPropertyValue("iptc:release_date", calendar);
    }
    doc.setPropertyValue("iptc:release_time", (String) metadata.get(META_RELEASE_TIME));
    doc.setPropertyValue("iptc:source", (String) metadata.get(META_SOURCE));
    doc.setPropertyValue("iptc:special_instructions", (String) metadata.get(META_SPECIAL_INSTRUCTIONS));
    doc.setPropertyValue("iptc:supplemental_categories", (String) metadata.get(META_SUPPLEMENTAL_CATEGORIES));
    doc.setPropertyValue("iptc:time_created", (String) metadata.get(META_TIME_CREATED));
    doc.setPropertyValue("iptc:urgency", (String) metadata.get(META_URGENCY));
    doc.setPropertyValue("iptc:writer", (String) metadata.get(META_WRITER));
}
Example 50
Project: android_geotagger-master  File: Debug.java View source code
public static void debug(String message, Object value) {
    if (value == null)
        debug(message, "null");
    else if (value instanceof char[])
        debug(message, (char[]) value);
    else if (value instanceof byte[])
        debug(message, (byte[]) value);
    else if (value instanceof int[])
        debug(message, (int[]) value);
    else if (value instanceof String)
        debug(message, (String) value);
    else if (value instanceof java.util.List)
        debug(message, (java.util.List) value);
    else if (value instanceof Map)
        debug(message, (Map) value);
    else //			debug(message, (ICC_Profile) value);
    if (value instanceof File)
        debug(message, (File) value);
    else if (value instanceof Date)
        debug(message, (Date) value);
    else if (value instanceof Calendar)
        debug(message, (Calendar) value);
    else
        debug(message, value.toString());
}
Example 51
Project: jai-imageio-core-master  File: TIFFImageReader.java View source code
public Iterator getImageTypes(int imageIndex) throws IIOException {
    // List of ImageTypeSpecifiers
    List l;
    Integer imageIndexInteger = new Integer(imageIndex);
    if (imageTypeMap.containsKey(imageIndexInteger)) {
        // Return the cached ITS List.
        l = (List) imageTypeMap.get(imageIndexInteger);
    } else {
        // Create a new ITS List.
        l = new ArrayList(1);
        // Create the ITS and cache if for later use so that this method
        // always returns an Iterator containing the same ITS objects.
        seekToImage(imageIndex);
        ImageTypeSpecifier itsRaw = TIFFDecompressor.getRawImageTypeSpecifier(photometricInterpretation, compression, samplesPerPixel, bitsPerSample, sampleFormat, extraSamples, colorMap);
        // Check for an ICCProfile field.
        TIFFField iccProfileField = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ICC_PROFILE);
        // to use it if the data layout is component type.
        if (iccProfileField != null && itsRaw.getColorModel() instanceof ComponentColorModel) {
            // Create a ColorSpace from the profile.
            byte[] iccProfileValue = iccProfileField.getAsBytes();
            ICC_Profile iccProfile = ICC_Profile.getInstance(iccProfileValue);
            ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(iccProfile);
            // Get the raw sample and color information.
            ColorModel cmRaw = itsRaw.getColorModel();
            ColorSpace csRaw = cmRaw.getColorSpace();
            SampleModel smRaw = itsRaw.getSampleModel();
            // Get the number of samples per pixel and the number
            // of color components.
            int numBands = smRaw.getNumBands();
            int numComponents = iccColorSpace.getNumComponents();
            // numbers of samples and color components are amenable.
            if (numBands == numComponents || numBands == numComponents + 1) {
                // Set alpha flags.
                boolean hasAlpha = numComponents != numBands;
                boolean isAlphaPre = hasAlpha && cmRaw.isAlphaPremultiplied();
                // Create a ColorModel of the same class and with
                // the same transfer type.
                ColorModel iccColorModel = new ComponentColorModel(iccColorSpace, cmRaw.getComponentSize(), hasAlpha, isAlphaPre, cmRaw.getTransparency(), cmRaw.getTransferType());
                // Prepend the ICC profile-based ITS to the List. The
                // ColorModel and SampleModel are guaranteed to be
                // compatible as the old and new ColorModels are both
                // ComponentColorModels with the same transfer type
                // and the same number of components.
                l.add(new ImageTypeSpecifier(iccColorModel, smRaw));
                // as the ICC ColorSpace.
                if (csRaw.getType() == iccColorSpace.getType() && csRaw.getNumComponents() == iccColorSpace.getNumComponents()) {
                    l.add(itsRaw);
                }
            } else {
                // ICCProfile not compatible with SampleModel.
                // Append the raw ITS to the List.
                l.add(itsRaw);
            }
        } else {
            // No ICCProfile field or raw ColorModel not component.
            // Append the raw ITS to the List.
            l.add(itsRaw);
        }
        // Cache the ITS List.
        imageTypeMap.put(imageIndexInteger, l);
    }
    return l.iterator();
}
Example 52
Project: jpexs-decompiler-master  File: CMYKJPEGImageReader.java View source code
public static BufferedImage read(ImageInputStream in, boolean inverseYCCKColors, boolean isIgnoreColorProfile) throws IOException {
    // Seek to start of input stream
    in.seek(0);
    // Extract metadata from the JFIF stream.
    // --------------------------------------
    // In particular, we are interested into the following fields:
    int samplePrecision = 0;
    int numberOfLines = 0;
    int numberOfSamplesPerLine = 0;
    int numberOfComponentsInFrame = 0;
    int app14AdobeColorTransform = 0;
    ByteArrayOutputStream app2ICCProfile = new ByteArrayOutputStream();
    // Browse for marker segments, and extract data from those
    // which are of interest.
    JFIFInputStream fifi = new JFIFInputStream(new ImageInputStreamAdapter(in));
    for (JFIFInputStream.Segment seg = fifi.getNextSegment(); seg != null; seg = fifi.getNextSegment()) {
        if (0xffc0 <= seg.marker && seg.marker <= 0xffc3 || 0xffc5 <= seg.marker && seg.marker <= 0xffc7 || 0xffc9 <= seg.marker && seg.marker <= 0xffcb || 0xffcd <= seg.marker && seg.marker <= 0xffcf) {
            // SOF0 - SOF15: Start of Frame Header marker segment
            DataInputStream dis = new DataInputStream(fifi);
            samplePrecision = dis.readUnsignedByte();
            numberOfLines = dis.readUnsignedShort();
            numberOfSamplesPerLine = dis.readUnsignedShort();
            numberOfComponentsInFrame = dis.readUnsignedByte();
            // Thus we can abort here.
            break;
        } else if (seg.marker == 0xffe2) {
            // APP2: Application-specific marker segment
            if (seg.length >= 26) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 12-bytes containing the null-terminated string: "ICC_PROFILE".
                if (dis.readLong() == 0x4943435f50524f46L && dis.readInt() == 0x494c4500) {
                    // Skip 2 bytes
                    dis.skipBytes(2);
                    // Read Adobe ICC_PROFILE int buffer. The profile is split up over
                    // multiple APP2 marker segments.
                    byte[] b = new byte[512];
                    for (int count = dis.read(b); count != -1; count = dis.read(b)) {
                        app2ICCProfile.write(b, 0, count);
                    }
                }
            }
        } else if (seg.marker == 0xffee) {
            // APP14: Application-specific marker segment
            if (seg.length == 12) {
                DataInputStream dis = new DataInputStream(fifi);
                // Check for 6-bytes containing the null-terminated string: "Adobe".
                if (dis.readInt() == 0x41646f62L && dis.readUnsignedShort() == 0x6500) {
                    int version = dis.readUnsignedByte();
                    int app14Flags0 = dis.readUnsignedShort();
                    int app14Flags1 = dis.readUnsignedShort();
                    app14AdobeColorTransform = dis.readUnsignedByte();
                }
            }
        }
    }
    //fifi.close();
    // Read the image data
    BufferedImage img = null;
    if (numberOfComponentsInFrame != 4) {
        // Read image with YCC color encoding.
        in.seek(0);
        //            img = readImageFromYCCorGray(in);
        img = readRGBImageFromYCC(new ImageInputStreamAdapter(in), null);
    } else if (numberOfComponentsInFrame == 4) {
        // Try to instantiate an ICC_Profile from the app2ICCProfile
        ICC_Profile profile = null;
        if (!isIgnoreColorProfile && app2ICCProfile.size() > 0) {
            try {
                profile = ICC_Profile.getInstance(new ByteArrayInputStream(app2ICCProfile.toByteArray()));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        switch(app14AdobeColorTransform) {
            case 0:
            default:
                // Read image with RGBA color encoding.
                in.seek(0);
                img = readRGBAImageFromRGBA(new ImageInputStreamAdapter(in), profile);
                break;
            case 1:
                throw new IOException("YCbCr not supported");
            case 2:
                // I case none has been supplied, we create a default one here.
                if (profile == null) {
                    profile = ICC_Profile.getInstance(CMYKJPEGImageReader.class.getResourceAsStream("Generic CMYK Profile.icc"));
                }
                in.seek(0);
                if (inverseYCCKColors) {
                    img = readRGBImageFromInvertedYCCK(new ImageInputStreamAdapter(in), profile);
                } else {
                    img = readRGBImageFromYCCK(new ImageInputStreamAdapter(in), profile);
                }
                break;
        }
    }
    return img;
}
Example 53
Project: sanselanandroid-master  File: Debug.java View source code
public static void debug(String message, Object value) {
    if (value == null)
        debug(message, "null");
    else if (value instanceof char[])
        debug(message, (char[]) value);
    else if (value instanceof byte[])
        debug(message, (byte[]) value);
    else if (value instanceof int[])
        debug(message, (int[]) value);
    else if (value instanceof String)
        debug(message, (String) value);
    else if (value instanceof java.util.List)
        debug(message, (java.util.List) value);
    else if (value instanceof Map)
        debug(message, (Map) value);
    else //			debug(message, (ICC_Profile) value);
    if (value instanceof File)
        debug(message, (File) value);
    else if (value instanceof Date)
        debug(message, (Date) value);
    else if (value instanceof Calendar)
        debug(message, (Calendar) value);
    else
        debug(message, value.toString());
}
Example 54
Project: secureOWS-master  File: ShortGridCoverage.java View source code
private BufferedImage createBufferedImage(int xAxis, int yAxis) {
    BufferedImage bi = null;
    int sampleDim = getNumSampleDimensions();
    switch(sampleDim) {
        case 1:
            {
                SampleModel sm = new BandedSampleModel(DataBuffer.TYPE_USHORT, xAxis, yAxis, 1);
                ICC_Profile prof = ICC_Profile.getInstance(ColorSpace.CS_GRAY);
                ColorSpace cs = new ICC_ColorSpace(prof);
                ComponentColorModel colorModel = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
                WritableRaster wraster = Raster.createWritableRaster(sm, new Point());
                bi = new BufferedImage(colorModel, wraster, false, null);
            }
    }
    return bi;
}
Example 55
Project: ae-awt-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 56
Project: ikvm-openjdk-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 57
Project: JDK-master  File: JPEGMetadata.java View source code
///// Writer support
void writeToStream(ImageOutputStream ios, boolean ignoreJFIF, boolean forceJFIF, List thumbnails, ICC_Profile iccProfile, boolean ignoreAdobe, int newAdobeTransform, JPEGImageWriter writer) throws IOException {
    if (forceJFIF) {
        // Write a default JFIF segment, including thumbnails
        // This won't be duplicated below because forceJFIF will be
        // set only if there is no JFIF present already.
        JFIFMarkerSegment.writeDefaultJFIF(ios, thumbnails, iccProfile, writer);
        if ((ignoreAdobe == false) && (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE)) {
            if ((newAdobeTransform != JPEG.ADOBE_UNKNOWN) && (newAdobeTransform != JPEG.ADOBE_YCC)) {
                // Not compatible, so ignore Adobe.
                ignoreAdobe = true;
                writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
            }
        }
    }
    // Iterate over each MarkerSegment
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof JFIFMarkerSegment) {
            if (ignoreJFIF == false) {
                JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
                jfif.writeWithThumbs(ios, thumbnails, writer);
                if (iccProfile != null) {
                    JFIFMarkerSegment.writeICC(iccProfile, ios);
                }
            }
        // Otherwise ignore it, as requested
        } else if (seg instanceof AdobeMarkerSegment) {
            if (ignoreAdobe == false) {
                if (newAdobeTransform != JPEG.ADOBE_IMPOSSIBLE) {
                    AdobeMarkerSegment newAdobe = (AdobeMarkerSegment) seg.clone();
                    newAdobe.transform = newAdobeTransform;
                    newAdobe.write(ios);
                } else if (forceJFIF) {
                    // If adobe isn't JFIF compatible, ignore it
                    AdobeMarkerSegment adobe = (AdobeMarkerSegment) seg;
                    if ((adobe.transform == JPEG.ADOBE_UNKNOWN) || (adobe.transform == JPEG.ADOBE_YCC)) {
                        adobe.write(ios);
                    } else {
                        writer.warningOccurred(JPEGImageWriter.WARNING_METADATA_ADJUSTED_FOR_THUMB);
                    }
                } else {
                    seg.write(ios);
                }
            }
        // Otherwise ignore it, as requested
        } else {
            seg.write(ios);
        }
    }
}
Example 58
Project: junrar-android-master  File: BMPImageReader.java View source code
public void readHeader() throws IOException {
    if (gotHeader)
        return;
    if (iis == null) {
        throw new IllegalStateException("Input source not set!");
    }
    int profileData = 0, profileSize = 0;
    this.metadata = new BMPMetadata();
    iis.mark();
    // read and check the magic marker
    byte[] marker = new byte[2];
    iis.read(marker);
    if (marker[0] != 0x42 || marker[1] != 0x4d)
        throw new IllegalArgumentException(I18N.getString("BMPImageReader1"));
    // Read file size
    bitmapFileSize = iis.readUnsignedInt();
    // skip the two reserved fields
    iis.skipBytes(4);
    // Offset to the bitmap from the beginning
    bitmapOffset = iis.readUnsignedInt();
    // End File Header
    // Start BitmapCoreHeader
    long size = iis.readUnsignedInt();
    if (size == 12) {
        width = iis.readShort();
        height = iis.readShort();
    } else {
        width = iis.readInt();
        height = iis.readInt();
    }
    metadata.width = width;
    metadata.height = height;
    int planes = iis.readUnsignedShort();
    bitsPerPixel = iis.readUnsignedShort();
    //metadata.colorPlane = planes;
    metadata.bitsPerPixel = (short) bitsPerPixel;
    // As BMP always has 3 rgb bands, except for Version 5,
    // which is bgra
    numBands = 3;
    if (size == 12) {
        // Windows 2.x and OS/2 1.x
        metadata.bmpVersion = VERSION_2;
        // Classify the image type
        if (bitsPerPixel == 1) {
            imageType = VERSION_2_1_BIT;
        } else if (bitsPerPixel == 4) {
            imageType = VERSION_2_4_BIT;
        } else if (bitsPerPixel == 8) {
            imageType = VERSION_2_8_BIT;
        } else if (bitsPerPixel == 24) {
            imageType = VERSION_2_24_BIT;
        }
        // Read in the palette
        int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 3);
        int sizeOfPalette = numberOfEntries * 3;
        palette = new byte[sizeOfPalette];
        iis.readFully(palette, 0, sizeOfPalette);
        metadata.palette = palette;
        metadata.paletteSize = numberOfEntries;
    } else {
        compression = iis.readUnsignedInt();
        imageSize = iis.readUnsignedInt();
        long xPelsPerMeter = iis.readInt();
        long yPelsPerMeter = iis.readInt();
        long colorsUsed = iis.readUnsignedInt();
        long colorsImportant = iis.readUnsignedInt();
        metadata.compression = (int) compression;
        metadata.xPixelsPerMeter = (int) xPelsPerMeter;
        metadata.yPixelsPerMeter = (int) yPelsPerMeter;
        metadata.colorsUsed = (int) colorsUsed;
        metadata.colorsImportant = (int) colorsImportant;
        if (size == 40) {
            // Windows 3.x and Windows NT
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    metadata.bmpVersion = VERSION_3;
                    imageType = VERSION_3_XP_EMBEDDED;
                    break;
                // No compression
                case BI_RGB:
                // 8-bit RLE compression
                case BI_RLE8:
                case // 4-bit RLE compression
                BI_RLE4:
                    // Read in the palette
                    int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
                    int sizeOfPalette = numberOfEntries * 4;
                    palette = new byte[sizeOfPalette];
                    iis.readFully(palette, 0, sizeOfPalette);
                    metadata.palette = palette;
                    metadata.paletteSize = numberOfEntries;
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_3_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_3_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_3_8_BIT;
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_3_24_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                        redMask = 0x7C00;
                        greenMask = 0x3E0;
                        // 0x1F;
                        blueMask = (1 << 5) - 1;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                        redMask = 0x00FF0000;
                        greenMask = 0x0000FF00;
                        blueMask = 0x000000FF;
                        metadata.redMask = redMask;
                        metadata.greenMask = greenMask;
                        metadata.blueMask = blueMask;
                    }
                    metadata.bmpVersion = VERSION_3;
                    break;
                case BI_BITFIELDS:
                    if (bitsPerPixel == 16) {
                        imageType = VERSION_3_NT_16_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_3_NT_32_BIT;
                    }
                    // BitsField encoding
                    redMask = (int) iis.readUnsignedInt();
                    greenMask = (int) iis.readUnsignedInt();
                    blueMask = (int) iis.readUnsignedInt();
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    if (colorsUsed != 0) {
                        // there is a palette
                        sizeOfPalette = (int) colorsUsed * 4;
                        palette = new byte[sizeOfPalette];
                        iis.readFully(palette, 0, sizeOfPalette);
                        metadata.palette = palette;
                        metadata.paletteSize = (int) colorsUsed;
                    }
                    metadata.bmpVersion = VERSION_3_NT;
                    break;
                default:
                    throw new RuntimeException(I18N.getString("BMPImageReader2"));
            }
        } else if (size == 108 || size == 124) {
            // Windows 4.x BMP
            if (size == 108)
                metadata.bmpVersion = VERSION_4;
            else if (size == 124)
                metadata.bmpVersion = VERSION_5;
            // rgb masks, valid only if comp is BI_BITFIELDS
            redMask = (int) iis.readUnsignedInt();
            greenMask = (int) iis.readUnsignedInt();
            blueMask = (int) iis.readUnsignedInt();
            // Only supported for 32bpp BI_RGB argb
            alphaMask = (int) iis.readUnsignedInt();
            long csType = iis.readUnsignedInt();
            int redX = iis.readInt();
            int redY = iis.readInt();
            int redZ = iis.readInt();
            int greenX = iis.readInt();
            int greenY = iis.readInt();
            int greenZ = iis.readInt();
            int blueX = iis.readInt();
            int blueY = iis.readInt();
            int blueZ = iis.readInt();
            long gammaRed = iis.readUnsignedInt();
            long gammaGreen = iis.readUnsignedInt();
            long gammaBlue = iis.readUnsignedInt();
            if (size == 124) {
                metadata.intent = iis.readInt();
                profileData = iis.readInt();
                profileSize = iis.readInt();
                iis.skipBytes(4);
            }
            metadata.colorSpace = (int) csType;
            if (csType == LCS_CALIBRATED_RGB) {
                // All the new fields are valid only for this case
                metadata.redX = redX;
                metadata.redY = redY;
                metadata.redZ = redZ;
                metadata.greenX = greenX;
                metadata.greenY = greenY;
                metadata.greenZ = greenZ;
                metadata.blueX = blueX;
                metadata.blueY = blueY;
                metadata.blueZ = blueZ;
                metadata.gammaRed = (int) gammaRed;
                metadata.gammaGreen = (int) gammaGreen;
                metadata.gammaBlue = (int) gammaBlue;
            }
            // Read in the palette
            int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
            int sizeOfPalette = numberOfEntries * 4;
            palette = new byte[sizeOfPalette];
            iis.readFully(palette, 0, sizeOfPalette);
            metadata.palette = palette;
            metadata.paletteSize = numberOfEntries;
            switch((int) compression) {
                case BI_JPEG:
                case BI_PNG:
                    if (size == 108) {
                        imageType = VERSION_4_XP_EMBEDDED;
                    } else if (size == 124) {
                        imageType = VERSION_5_XP_EMBEDDED;
                    }
                    break;
                default:
                    if (bitsPerPixel == 1) {
                        imageType = VERSION_4_1_BIT;
                    } else if (bitsPerPixel == 4) {
                        imageType = VERSION_4_4_BIT;
                    } else if (bitsPerPixel == 8) {
                        imageType = VERSION_4_8_BIT;
                    } else if (bitsPerPixel == 16) {
                        imageType = VERSION_4_16_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x7C00;
                            greenMask = 0x3E0;
                            blueMask = 0x1F;
                        }
                    } else if (bitsPerPixel == 24) {
                        imageType = VERSION_4_24_BIT;
                    } else if (bitsPerPixel == 32) {
                        imageType = VERSION_4_32_BIT;
                        if ((int) compression == BI_RGB) {
                            redMask = 0x00FF0000;
                            greenMask = 0x0000FF00;
                            blueMask = 0x000000FF;
                        }
                    }
                    metadata.redMask = redMask;
                    metadata.greenMask = greenMask;
                    metadata.blueMask = blueMask;
                    metadata.alphaMask = alphaMask;
            }
        } else {
            throw new RuntimeException(I18N.getString("BMPImageReader3"));
        }
    }
    if (height > 0) {
        // bottom up image
        isBottomUp = true;
    } else {
        // top down image
        isBottomUp = false;
        height = Math.abs(height);
    }
    // Reset Image Layout so there's only one tile.
    //Define the color space
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    if (metadata.colorSpace == PROFILE_LINKED || metadata.colorSpace == PROFILE_EMBEDDED) {
        iis.mark();
        iis.skipBytes(profileData - size);
        byte[] profile = new byte[profileSize];
        iis.readFully(profile, 0, profileSize);
        iis.reset();
        try {
            if (metadata.colorSpace == PROFILE_LINKED)
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(new String(profile)));
            else
                colorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(profile));
        } catch (Exception e) {
            colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        }
    }
    if (bitsPerPixel == 0 || compression == BI_JPEG || compression == BI_PNG) {
        // the colorModel and sampleModel will be initialzed
        // by the  reader of embedded image
        colorModel = null;
        sampleModel = null;
    } else if (bitsPerPixel == 1 || bitsPerPixel == 4 || bitsPerPixel == 8) {
        // When number of bitsPerPixel is <= 8, we use IndexColorModel.
        numBands = 1;
        if (bitsPerPixel == 8) {
            int[] bandOffsets = new int[numBands];
            for (int i = 0; i < numBands; i++) {
                bandOffsets[i] = numBands - 1 - i;
            }
            sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        } else {
            // 1 and 4 bit pixels can be stored in a packed format.
            sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitsPerPixel);
        }
        // Create IndexColorModel from the palette.
        byte r[], g[], b[];
        if (imageType == VERSION_2_1_BIT || imageType == VERSION_2_4_BIT || imageType == VERSION_2_8_BIT) {
            size = palette.length / 3;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < (int) size; i++) {
                off = 3 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        } else {
            size = palette.length / 4;
            if (size > 256) {
                size = 256;
            }
            int off;
            r = new byte[(int) size];
            g = new byte[(int) size];
            b = new byte[(int) size];
            for (int i = 0; i < size; i++) {
                off = 4 * i;
                b[i] = palette[off];
                g[i] = palette[off + 1];
                r[i] = palette[off + 2];
            }
        }
        if (ImageUtil.isIndicesForGrayscale(r, g, b))
            colorModel = ImageUtil.createColorModel(null, sampleModel);
        else
            colorModel = new IndexColorModel(bitsPerPixel, (int) size, r, g, b);
    } else if (bitsPerPixel == 16) {
        numBands = 3;
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_USHORT, width, height, new int[] { redMask, greenMask, blueMask });
        colorModel = new DirectColorModel(colorSpace, 16, redMask, greenMask, blueMask, 0, false, DataBuffer.TYPE_USHORT);
    } else if (bitsPerPixel == 32) {
        numBands = alphaMask == 0 ? 3 : 4;
        // The number of bands in the SampleModel is determined by
        // the length of the mask array passed in.
        int[] bitMasks = numBands == 3 ? new int[] { redMask, greenMask, blueMask } : new int[] { redMask, greenMask, blueMask, alphaMask };
        sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, bitMasks);
        colorModel = new DirectColorModel(colorSpace, 32, redMask, greenMask, blueMask, alphaMask, false, DataBuffer.TYPE_INT);
    } else {
        numBands = 3;
        // Create SampleModel
        int[] bandOffsets = new int[numBands];
        for (int i = 0; i < numBands; i++) {
            bandOffsets[i] = numBands - 1 - i;
        }
        sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, numBands, numBands * width, bandOffsets);
        colorModel = ImageUtil.createColorModel(colorSpace, sampleModel);
    }
    originalSampleModel = sampleModel;
    originalColorModel = colorModel;
    // Reset to the start of bitmap; then jump to the
    //start of image data
    iis.reset();
    iis.skipBytes(bitmapOffset);
    gotHeader = true;
}
Example 59
Project: color4j-master  File: IccSupport.java View source code
public static void setICCMonitorProfile(String fileName) throws IOException {
    if (fileName != null && fileName.length() > 0) {
        ICC_Profile profile = ICC_Profile.getInstance(fileName);
        m_ICCDisplayColorSpace = new ICC_ColorSpace(profile);
    }
}
Example 60
Project: IKVM.NET-cvs-clone-master  File: LCMS.java View source code
public void getTagData(long profileID, int tagSignature, byte[] data) {
    if (tagSignature == ICC_Profile.icSigHead) {
        byte[] src = profiles.get((int) profileID);
        System.arraycopy(src, 0, data, 0, 128);
        return;
    }
    throw new CMMException("Not implemented");
}
Example 61
Project: dcm4che-master  File: ColorModelFactory.java View source code
private static ColorSpace createRGBColorSpace(byte[] iccProfile) {
    if (iccProfile != null)
        return new ICC_ColorSpace(ICC_Profile.getInstance(iccProfile));
    return ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
Example 62
Project: haskell-java-parser-master  File: ColorConvertOp.java View source code
public ICC_Profile[] getICC_Profiles() {
    return profiles;
}