Example usage for java.awt.color ColorSpace CS_sRGB

List of usage examples for java.awt.color ColorSpace CS_sRGB

Introduction

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

Prototype

int CS_sRGB

To view the source code for java.awt.color ColorSpace CS_sRGB.

Click Source Link

Document

The sRGB color space defined at <a href="http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html"> http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html</a>.

Usage

From source file:ComponentTest.java

public static void main(String[] args) {
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(cs, new int[] { 5, 6, 5 }, false, false, Transparency.OPAQUE,
            DataBuffer.TYPE_BYTE);

    Color fifty = new Color(cs, new float[] { 1.0f, 1.0f, 1.0f }, 0);
    float[] components = fifty.getComponents(null);
    System.out.print("Original normalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(components[i] + " ");
    System.out.println();/* www  .j  a va2 s  .com*/
    int[] unnormalized = cm.getUnnormalizedComponents(components, 0, null, 0);
    System.out.print("Original unnormalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(unnormalized[i] + " ");
    System.out.println();
    Object pixel = cm.getDataElements(unnormalized, 0, (Object) null);
    System.out.print("Pixel samples: ");
    byte[] pixelBytes = (byte[]) pixel;
    for (int i = 0; i < 3; i++)
        System.out.print(pixelBytes[i] + " ");
    System.out.println();

    unnormalized = cm.getComponents(pixel, null, 0);
    System.out.print("Derived unnormalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(unnormalized[i] + " ");
    System.out.println();
    components = cm.getNormalizedComponents(unnormalized, 0, null, 0);
    System.out.print("Derived normalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(components[i] + " ");
    System.out.println();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(cs, new int[] { 5, 6, 5 }, false, false, Transparency.OPAQUE,
            DataBuffer.TYPE_BYTE);

    Color fifty = new Color(cs, new float[] { 1.0f, 1.0f, 1.0f }, 0);
    float[] components = fifty.getComponents(null);
    System.out.print("Original normalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(components[i] + " ");
    System.out.println();//w w w  . java 2 s.  c o  m
    int[] unnormalized = cm.getUnnormalizedComponents(components, 0, null, 0);
    System.out.print("Original unnormalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(unnormalized[i] + " ");
    System.out.println();

    Object pixel = cm.getDataElements(unnormalized, 0, (Object) null);
    System.out.print("Pixel samples: ");
    byte[] pixelBytes = (byte[]) pixel;
    for (int i = 0; i < 3; i++)
        System.out.print(pixelBytes[i] + " ");
    System.out.println();

    unnormalized = cm.getComponents(pixel, null, 0);
    System.out.print("Derived unnormalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(unnormalized[i] + " ");
    System.out.println();
    components = cm.getNormalizedComponents(unnormalized, 0, null, 0);
    System.out.print("Derived normalized components: ");
    for (int i = 0; i < 3; i++)
        System.out.print(components[i] + " ");
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.ShadingContext.java

/**
 * Constructor./*w  w w.j a v a 2  s .c  om*/
 *
 * @param shading the shading type to be used
 * @param cm the color model to be used
 * @param xform transformation for user to device space
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @throws java.io.IOException if there is an error getting the color space
 * or doing background color conversion.
 */
public ShadingContext(PDShading shading, ColorModel cm, AffineTransform xform, Matrix matrix)
        throws IOException {
    this.shading = shading;
    shadingColorSpace = shading.getColorSpace();

    // create the output color model using RGB+alpha as color space
    ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT,
            DataBuffer.TYPE_BYTE);

    bboxRect = shading.getBBox();
    if (bboxRect != null) {
        transformBBox(matrix, xform);
    }

    // get background values if available
    COSArray bg = shading.getBackground();
    if (bg != null) {
        background = bg.toFloatArray();
        rgbBackground = convertToRGB(background);
    }
}

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

/**
 * Load the ICC profile, or init alternateColorSpace color space.
 *//* w  w w  . j  a  va  2  s . com*/
private void loadICCProfile() throws IOException {
    InputStream input = null;
    try {
        input = this.stream.createInputStream();

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

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

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

From source file:org.apache.fop.pdf.PDFICCBasedColorSpace.java

/**
 * Sets up the sRGB color profile in the PDF document. It does so by trying to
 * install a very small ICC profile (~4KB) instead of the very big one (~140KB)
 * the Sun JVM uses.//from ww w . jav  a2s .  c  om
 * @param pdfDoc the PDF document
 * @return the ICC stream with the sRGB profile
 */
public static PDFICCStream setupsRGBColorProfile(PDFDocument pdfDoc) {
    ICC_Profile profile;
    PDFICCStream sRGBProfile = pdfDoc.getFactory().makePDFICCStream();
    InputStream in = PDFDocument.class.getResourceAsStream("sRGB Color Space Profile.icm");
    if (in != null) {
        try {
            profile = ColorProfileUtil.getICC_Profile(in);
        } catch (IOException ioe) {
            throw new RuntimeException("Unexpected IOException loading the sRGB profile: " + ioe.getMessage());
        } finally {
            IOUtils.closeQuietly(in);
        }
    } else {
        // Fallback: Use the sRGB profile from the JRE (about 140KB)
        profile = ColorProfileUtil.getICC_Profile(ColorSpace.CS_sRGB);
    }
    sRGBProfile.setColorSpace(profile, null);
    return sRGBProfile;
}

From source file:org.apache.pdfbox.rendering.TilingPaint.java

/**
 * Returns the pattern image in parent stream coordinates.
 *///  w  ww  .  j  av a  2s . com
private BufferedImage getImage(PageDrawer drawer, PDTilingPattern pattern, PDColorSpace colorSpace,
        PDColor color, AffineTransform xform, Rectangle2D anchorRect) throws IOException {
    ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT,
            DataBuffer.TYPE_BYTE);

    float width = (float) Math.abs(anchorRect.getWidth());
    float height = (float) Math.abs(anchorRect.getHeight());

    // device scale transform (i.e. DPI) (see PDFBOX-1466.pdf)
    Matrix xformMatrix = new Matrix(xform);
    float xScale = Math.abs(xformMatrix.getScalingFactorX());
    float yScale = Math.abs(xformMatrix.getScalingFactorY());
    width *= xScale;
    height *= yScale;

    int rasterWidth = Math.max(1, ceiling(width));
    int rasterHeight = Math.max(1, ceiling(height));

    // create raster
    WritableRaster raster = cm.createCompatibleWritableRaster(rasterWidth, rasterHeight);
    BufferedImage image = new BufferedImage(cm, raster, false, null);

    Graphics2D graphics = image.createGraphics();

    // flip a -ve YStep around its own axis (see gs-bugzilla694385.pdf)
    if (pattern.getYStep() < 0) {
        graphics.translate(0, rasterHeight);
        graphics.scale(1, -1);
    }

    // flip a -ve XStep around its own axis
    if (pattern.getXStep() < 0) {
        graphics.translate(rasterWidth, 0);
        graphics.scale(-1, 1);
    }

    // device scale transform (i.e. DPI)
    graphics.scale(xScale, yScale);

    // apply only the scaling from the pattern transform, doing scaling here improves the
    // image quality and prevents large scale-down factors from creating huge tiling cells.
    Matrix newPatternMatrix;
    newPatternMatrix = Matrix.getScaleInstance(Math.abs(patternMatrix.getScalingFactorX()),
            Math.abs(patternMatrix.getScalingFactorY()));

    // move origin to (0,0)
    newPatternMatrix.concatenate(Matrix.getTranslateInstance(-pattern.getBBox().getLowerLeftX(),
            -pattern.getBBox().getLowerLeftY()));

    // render using PageDrawer
    drawer.drawTilingPattern(graphics, pattern, colorSpace, color, newPatternMatrix);
    graphics.dispose();

    return image;
}

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

public ImageRawPNG getImageRawPNG(final ImageInfo info) throws ImageException, IOException {
    try (final InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec))) {
        switch (this.colorType) {
        case PNG_COLOR_GRAY:
            if (this.hasPalette) {
                throw new ImageException("Corrupt PNG: color palette is not allowed!");
            }/*from w ww . j  av a2 s  .co m*/
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
                    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_RGB:
            // actually a check of the sRGB chunk would be necessary to
            // confirm
            // if it's really sRGB
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false,
                    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_PALETTE:
            if (this.hasAlphaPalette) {
                this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                        this.greenPalette, this.bluePalette, this.alphaPalette);
            } else {
                this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                        this.greenPalette, this.bluePalette);
            }
            break;
        case PNG_COLOR_GRAY_ALPHA:
            if (this.hasPalette) {
                throw new ImageException("Corrupt PNG: color palette is not allowed!");
            }
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false,
                    Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
            break;
        case PNG_COLOR_RGB_ALPHA:
            // actually a check of the sRGB chunk would be necessary to
            // confirm
            // if it's really sRGB
            this.colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false,
                    Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
            break;
        default:
            throw new ImageException("Unsupported color type: " + this.colorType);
        }
        // the iccProfile is still null for now
        final ImageRawPNG rawImage = new ImageRawPNG(info, seqStream, this.colorModel, this.bitDepth,
                this.iccProfile);
        if (this.isTransparent) {
            if (this.colorType == PNG_COLOR_GRAY) {
                rawImage.setGrayTransparentAlpha(this.grayTransparentAlpha);
            } else if (this.colorType == PNG_COLOR_RGB) {
                rawImage.setRGBTransparentAlpha(this.redTransparentAlpha, this.greenTransparentAlpha,
                        this.blueTransparentAlpha);
            } else if (this.colorType == PNG_COLOR_PALETTE) {
                rawImage.setTransparent();
            } else {
                //
            }
        }
        return rawImage;
    }
}

From source file:com.alvermont.terraj.planet.io.ImageBuilder.java

/**
 * Create and return a <code>BufferedImage</code> object from the
 * result of the projection. This image can then be further processed
 * or written out to a file using <code>ImageIO</code>.
 *
 * @param proj The projection that will provide the image
 * @return A <code>BufferedImage</code> object containing the results of
 * the projection./* w ww  . j  a  va2 s .  co  m*/
 */
public BufferedImage getImage(Projector proj) {
    // get the pixel data and store it into a data buffer
    final byte[] pixels = getPixels(proj);

    final DataBuffer db = new DataBufferByte(pixels, pixels.length);

    // set up offsets for the R,G,B elements
    final int[] offsets = new int[3];

    offsets[0] = 0;
    offsets[1] = 1;
    offsets[2] = 2;

    // create the raster from the pixel data
    final int height = proj.getParameters().getProjectionParameters().getHeight();
    final int width = proj.getParameters().getProjectionParameters().getWidth();

    final WritableRaster raster = Raster.createInterleavedRaster(db, width, height, width * 3, 3, offsets,
            null);

    // create a colour model that matches the raster we have
    final ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false,
            Transparency.OPAQUE, DataBuffer.TYPE_BYTE);

    // combine raster and colour model into a buffered image
    final BufferedImage img = new BufferedImage(cm, raster, false, null);

    return img;
}

From source file:nitf.imageio.NITFReader.java

@Override
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException {
    checkIndex(imageIndex);//from   w  w  w .ja va2 s . c  o m

    List<ImageTypeSpecifier> l = new ArrayList<ImageTypeSpecifier>();

    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        String irep = subheader.getImageRepresentation().getStringData().trim();
        String pvType = subheader.getPixelValueType().getStringData().trim();
        int bandCount = subheader.getBandCount();
        int nbpp = subheader.getNumBitsPerPixel().getIntData();

        // if (NITFUtils.isCompressed(record, imageIndex))
        // {
        // throw new NotImplementedException(
        // "Only uncompressed imagery is currently supported");
        // }
        int nBytes = ((nbpp - 1) / 8) + 1;
        if (nBytes == 1 || nBytes == 2 || (nBytes == 4 && pvType.equals("R"))
                || (nBytes == 8 && pvType.equals("R"))) {
            if (nBytes == 1 && bandCount == 3 && irep.equals("RGB")) {
                ColorSpace rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
                int[] bandOffsets = new int[3];
                for (int i = 0; i < bandOffsets.length; ++i)
                    bandOffsets[i] = i;
                l.add(ImageTypeSpecifier.createInterleaved(rgb, bandOffsets, DataBuffer.TYPE_BYTE, false,
                        false));
            }
            l.add(ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE, false));
        } else {
            throw new NotImplementedException(
                    "Support for pixels of size " + nbpp + " bytes has not been implemented yet");
        }
    } catch (NITFException e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
    return l.iterator();
}

From source file:org.apache.fop.pdf.PDFColorHandler.java

private void establishDeviceRGB(StringBuffer codeBuffer, Color color, boolean fill) {
    float[] comps;
    if (color.getColorSpace().isCS_sRGB()) {
        comps = color.getColorComponents(null);
    } else {/*from ww  w  . j  a  va 2s .c  o m*/
        if (log.isDebugEnabled()) {
            log.debug("Converting color to sRGB as a fallback: " + color);
        }
        ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        comps = color.getColorComponents(sRGB, null);
    }
    if (ColorUtil.isGray(color)) {
        comps = new float[] { comps[0] }; //assuming that all components are the same
        writeColor(codeBuffer, comps, 1, (fill ? "g" : "G"));
    } else {
        writeColor(codeBuffer, comps, 3, (fill ? "rg" : "RG"));
    }
}