Example usage for java.awt.color ColorSpace CS_GRAY

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

Introduction

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

Prototype

int CS_GRAY

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

Click Source Link

Document

The built-in linear gray scale color space.

Usage

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

private void createImageStream(PDDocument doc, BufferedImage bi) throws IOException {
    BufferedImage alphaImage = null;
    BufferedImage rgbImage = null;
    int width = bi.getWidth();
    int height = bi.getHeight();
    if (bi.getColorModel().hasAlpha()) {
        // extract the alpha information
        WritableRaster alphaRaster = bi.getAlphaRaster();
        ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        alphaImage = new BufferedImage(cm, alphaRaster, false, null);
        // create a RGB image without alpha
        rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = rgbImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(bi, 0, 0, null);/*w  w w.  j a  v  a  2 s. com*/
    } else {
        rgbImage = bi;
    }
    java.io.OutputStream os = null;
    try {
        int numberOfComponents = rgbImage.getColorModel().getNumComponents();
        if (numberOfComponents == 3) {
            setColorSpace(PDDeviceRGB.INSTANCE);
        } else {
            if (numberOfComponents == 1) {
                setColorSpace(new PDDeviceGray());
            } else {
                throw new IllegalStateException();
            }
        }
        byte[] outData = new byte[width * height * numberOfComponents];
        rgbImage.getData().getDataElements(0, 0, width, height, outData);
        // add FlateDecode compression
        getPDStream().addCompression();
        os = getCOSStream().createUnfilteredStream();
        os.write(outData);

        COSDictionary dic = getCOSStream();
        dic.setItem(COSName.FILTER, COSName.FLATE_DECODE);
        dic.setItem(COSName.SUBTYPE, COSName.IMAGE);
        dic.setItem(COSName.TYPE, COSName.XOBJECT);
        if (alphaImage != null) {
            PDPixelMap smask = new PDPixelMap(doc, alphaImage);
            dic.setItem(COSName.SMASK, smask);
        }
        setBitsPerComponent(8);
        setHeight(height);
        setWidth(width);
    } finally {
        os.close();
    }
}

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

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    if (!MimeConstants.MIME_JPEG.equals(info.getMimeType())) {
        throw new IllegalArgumentException(
                "ImageInfo must be from a image with MIME type: " + MimeConstants.MIME_JPEG);
    }//from   www .jav a  2  s  . c o m

    ColorSpace colorSpace = null;
    boolean appeFound = false;
    int sofType = 0;
    ByteArrayOutputStream iccStream = null;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream in = ImageUtil.needImageInputStream(src);
    JPEGFile jpeg = new JPEGFile(in);
    in.mark();
    try {
        outer: while (true) {
            int reclen;
            int segID = jpeg.readMarkerSegment();
            if (log.isTraceEnabled()) {
                log.trace("Seg Marker: " + Integer.toHexString(segID));
            }
            switch (segID) {
            case EOI:
                log.trace("EOI found. Stopping.");
                break outer;
            case SOS:
                log.trace("SOS found. Stopping early."); //TODO Not sure if this is safe
                break outer;
            case SOI:
            case NULL:
                break;
            case SOF0: //baseline
            case SOF1: //extended sequential DCT
            case SOF2: //progressive (since PDF 1.3)
            case SOFA: //progressive (since PDF 1.3)
                sofType = segID;
                if (log.isTraceEnabled()) {
                    log.trace("SOF: " + Integer.toHexString(sofType));
                }
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    in.skipBytes(1); //data precision
                    in.skipBytes(2); //height
                    in.skipBytes(2); //width
                    int numComponents = in.readUnsignedByte();
                    if (numComponents == 1) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
                    } else if (numComponents == 3) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
                    } else if (numComponents == 4) {
                        colorSpace = DeviceCMYKColorSpace.getInstance();
                    } else {
                        throw new ImageException("Unsupported ColorSpace for image " + info
                                + ". The number of components supported are 1, 3 and 4.");
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APP2: //ICC (see ICC1V42.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for ICC profile
                    byte[] iccString = new byte[11];
                    in.readFully(iccString);
                    in.skipBytes(1); //string terminator (null byte)

                    if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) {
                        in.skipBytes(2); //chunk sequence number and total number of chunks
                        int payloadSize = reclen - 2 - 12 - 2;
                        if (ignoreColorProfile(hints)) {
                            log.debug("Ignoring ICC profile data in JPEG");
                            in.skipBytes(payloadSize);
                        } else {
                            byte[] buf = new byte[payloadSize];
                            in.readFully(buf);
                            if (iccStream == null) {
                                if (log.isDebugEnabled()) {
                                    log.debug("JPEG has an ICC profile");
                                    DataInputStream din = new DataInputStream(new ByteArrayInputStream(buf));
                                    log.debug("Declared ICC profile size: " + din.readInt());
                                }
                                //ICC profiles can be split into several chunks
                                //so collect in a byte array output stream
                                iccStream = new ByteArrayOutputStream();
                            }
                            iccStream.write(buf);
                        }
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APPE: //Adobe-specific (see 5116.DCT_Filter.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for Adobe header
                    byte[] adobeHeader = new byte[5];
                    in.readFully(adobeHeader);

                    if ("Adobe".equals(new String(adobeHeader, "US-ASCII"))) {
                        // The reason for reading the APPE marker is that Adobe Photoshop
                        // generates CMYK JPEGs with inverted values. The correct thing
                        // to do would be to interpret the values in the marker, but for now
                        // only assume that if APPE marker is present and colorspace is CMYK,
                        // the image is inverted.
                        appeFound = true;
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            default:
                jpeg.skipCurrentMarkerSegment();
            }
        }
    } finally {
        in.reset();
    }

    ICC_Profile iccProfile = buildICCProfile(info, colorSpace, iccStream);
    if (iccProfile == null && colorSpace == null) {
        throw new ImageException("ColorSpace could not be identified for JPEG image " + info);
    }

    boolean invertImage = false;
    if (appeFound && colorSpace.getType() == ColorSpace.TYPE_CMYK) {
        if (log.isDebugEnabled()) {
            log.debug("JPEG has an Adobe APPE marker. Note: CMYK Image will be inverted. ("
                    + info.getOriginalURI() + ")");
        }
        invertImage = true;
    }

    ImageRawJPEG rawImage = new ImageRawJPEG(info, ImageUtil.needInputStream(src), sofType, colorSpace,
            iccProfile, invertImage);
    return rawImage;
}

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 a va  2s .  c o 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:org.deegree.ogcwebservices.wms.dataaccess.ID2PInterpolation.java

private void createImage() {

    ColorModel ccm;//  ww  w  . j a  v a2 s  .c o m

    if (use32Bits) {
        image = new BufferedImage(getMap.getWidth(), getMap.getHeight(), BufferedImage.TYPE_INT_ARGB);
    } else {
        ccm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), null, false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
        WritableRaster wr = ccm.createCompatibleWritableRaster(getMap.getWidth(), getMap.getHeight());
        image = new BufferedImage(ccm, wr, false, new Hashtable<Object, Object>());
    }
}

From source file:org.geoserver.catalog.CoverageViewReader.java

private ColorModel getColorModelWithAlpha(int currentBandCount) {
    if (currentBandCount == 3) {
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        int[] nBits = { 8, 8, 8, 8 };
        return new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    } else if (currentBandCount == 1) {
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        int[] nBits = { 8, 8 };
        return new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    } else {/*w w w .  j  a  v a  2  s .  co  m*/
        throw new IllegalArgumentException("Cannot create a color model with alpha" + "support starting with "
                + currentBandCount + " bands");
    }
}

From source file:org.photovault.dcraw.DCRawReaderOp.java

public DCRawReaderOp(File f, RenderingHints hints) {
    super(null, hints, null, 1, 1, 1, 1);
    file = f;/*  ww w .j av a2s . c om*/
    lrd = lr.libraw_init(0);
    lrd.output_params.half_size = 1;
    lr.libraw_open_file(lrd, f.getAbsolutePath());
    sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, lrd.sizes.width, lrd.sizes.height, 1,
            lrd.sizes.width, new int[] { 0 });
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorModel c = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
    ImageLayout il = new ImageLayout(0, 0, 256, 256, sampleModel, c);
    setImageLayout(il);
    minX = 0;
    minY = 0;
    width = lrd.sizes.width;
    height = lrd.sizes.height;
    bayerfilter = lrd.idata.filters;
    cam_mul = lrd.color.cam_mul;
    setProperty("bayerfilter", lrd.idata.filters);
    setProperty("dcraw_cam_mul", cam_mul);
    setProperty("dcraw_cam_xyz", lrd.color.cam_xyz);
    setProperty("dcraw_rgb_cam", lrd.color.rgb_cam);
    setProperty("dcraw_black", lrd.color.black);
    setProperty("dcraw_max", lrd.color.maximum);
    setProperty("dcraw_black", lrd.color.black);
    setProperty("dcraw_margin_top", lrd.sizes.top_margin);
    setProperty("dcraw_margin_left", lrd.sizes.left_margin);
}

From source file:org.polymap.core.data.image.ImageGrayscaleProcessor.java

protected Image grayscale(Image image) {
    long start = System.currentTimeMillis();

    // load image data
    new javax.swing.ImageIcon(image).getImage();

    if (!(image instanceof BufferedImage)) {
        BufferedImage bimage = new BufferedImage(image.getHeight(null), image.getWidth(null),
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics g = bimage.getGraphics();
        g.drawImage(image, 0, 0, null);//from w ww  . jav  a 2s .co  m
        g.dispose();

        image = bimage;
    }

    // grayscale
    ColorConvertOp filter = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

    BufferedImage grayImage = new BufferedImage(image.getHeight(null), image.getWidth(null),
            BufferedImage.TYPE_4BYTE_ABGR);

    Graphics g = grayImage.getGraphics();
    filter.filter((BufferedImage) image, grayImage);
    g.dispose();

    log.info("Gray scaling took: " + (System.currentTimeMillis() - start) + "ms");
    return grayImage;
}

From source file:org.polymap.rhei.batik.engine.svg.Svg2Png.java

public static BufferedImage transform(BufferedImage img, ImageConfiguration imageConfiguration) {
    ColorSpace imgCS = img.getColorModel().getColorSpace();
    ColorSpace grayCS = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorConvertOp cop = new ColorConvertOp(imgCS, grayCS, null);
    BufferedImage finalThresholdImage = cop.filter(img, null);
    finalThresholdImage = shiftHue(finalThresholdImage, imageConfiguration);
    return finalThresholdImage;
}

From source file:org.shaman.terrain.polygonal.GraphToHeightmap.java

private void saveMatrix(float[][] matrix, String filename, float min, float max) {
    byte[] buffer = new byte[size * size];
    int i = 0;//  www  .jav  a 2s. c  o m
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            buffer[i] = (byte) ((matrix[x][y] - min) * 255 / (max - min));
            i++;
        }
    }
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    int[] nBits = { 8 };
    ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    SampleModel sm = cm.createCompatibleSampleModel(size, size);
    DataBufferByte db = new DataBufferByte(buffer, size * size);
    WritableRaster raster = Raster.createWritableRaster(sm, db, null);
    BufferedImage result = new BufferedImage(cm, raster, false, null);
    try {
        ImageIO.write(result, "png", new File(filename));
    } catch (IOException ex) {
        Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:paintbasico2d.VentanaPrincipal.java

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