Example usage for java.awt.color ColorSpace CS_LINEAR_RGB

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

Introduction

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

Prototype

int CS_LINEAR_RGB

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

Click Source Link

Document

A built-in linear RGB color space.

Usage

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

    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.freecine.filmscan.ScanStrip.java

/**
 Load the scan strip image from disk// w  ww .j av a 2 s . c om
 */
private void loadImage() {
    ImageReader reader;
    try {
        //        PlanarImage img = JAI.create( "fileload", fname );
        ImageInputStream istrm = new FileImageInputStream(file);
        reader = ImageIO.getImageReadersByFormatName("TIFF").next();
        reader.setInput(istrm);
        ImageReadParam param = reader.getDefaultReadParam();

        /*
         Set the color mode to linear sRGB as we don't have a better profile
         for the scanner/film available
         */
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
        ImageLayout layout = new ImageLayout();
        ColorModel cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
        layout.setColorModel(cm);
        RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
        stripImage = ImageReadDescriptor.create(istrm, 0, false, false, false, null, null, param, reader,
                hints);
        System.out.println("Color model " + stripImage.getColorModel());
        // BufferedImage inImg = reader.read( 0, param );            
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        log.error("Strip file " + file + " not found", ex);
    } catch (IOException ex) {
        log.error("IO error reading strip " + file + ": ", ex);
    }
}

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

static private ImageLayout layoutHelper(RenderedImage src, int downSample) {
    int width = src.getWidth() / downSample;
    int height = src.getHeight() / downSample;
    PixelInterleavedSampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, width,
            height, 3, width * 3, new int[] { 0, 1, 2 });
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    ColorModel c = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
    ImageLayout il = new ImageLayout(0, 0, 256, 256, sampleModel, c);
    il.setWidth(width);/* www .  j a  va 2  s .co  m*/
    il.setHeight(height);
    return il;
}

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

/**
 * Load the raw image using dcraw. No processing is yet done for the image,
 * however, the histogram & white point is calculated.
 *//*from  www  . j  a v a 2 s.  co  m*/
private void loadRawImage() {
    long startTime = System.currentTimeMillis();
    log.debug("begin:loadRawImage");
    if (lrd == null) {
        openRaw();
        log.debug("openRaw() " + (System.currentTimeMillis() - startTime));
        if (lrd == null) {
            throw new IllegalStateException("Called loadRawImage before opening file");
        }
        lr.libraw_unpack(lrd);
        log.debug("unpacked " + (System.currentTimeMillis() - startTime));
    }
    /*
     * Copy the unprocessed data to temporary array so that we can restore 
     * lrd to the state it had after unpack()
     */

    int oldFlags = lrd.progress_flags;
    int oldFilters = lrd.idata.filters;
    int rawImageSize = lrd.sizes.iwidth * lrd.sizes.iheight * 4;
    short rawWidth = lrd.sizes.width;
    short rawHeight = lrd.sizes.height;
    this.width = lrd.sizes.width;
    this.height = lrd.sizes.height;
    short[] rawData = lrd.image.getShortArray(0, rawImageSize);
    lr.libraw_dcraw_process(lrd);
    log.debug("processed " + (System.currentTimeMillis() - startTime));
    int procWidth = lrd.sizes.width;
    int procHeight = lrd.sizes.height;

    int postSubsample = (lrd.output_params.half_size > 0) ? subsample / 2 : subsample;
    /*
     * Copy the raw image to Java raster, using box filter to subsample
     */
    int scaledW = procWidth / postSubsample;
    int scaledH = procHeight / postSubsample;
    short[] buf = new short[scaledW * scaledH * 3];
    int pos = 0;
    for (int row = 0; row < scaledH; row++) {
        for (int col = 0; col < scaledW; col++) {
            int rsum = 0;
            int gsum = 0;
            int bsum = 0;
            for (int or = row * postSubsample; or < (row + 1) * postSubsample; or++) {
                for (int oc = col * postSubsample; oc < (col + 1) * postSubsample; oc++) {
                    int r = lrd.image.getShort(8 * (oc + procWidth * or));
                    rsum += (r & 0xffff);
                    int g = lrd.image.getShort(8 * (oc + procWidth * or) + 2);
                    gsum += (g & 0xffff);
                    int b = lrd.image.getShort(8 * (oc + procWidth * or) + 4);
                    bsum += (b & 0xffff);
                }
            }
            buf[pos++] = (short) (rsum / (postSubsample * postSubsample));
            buf[pos++] = (short) (gsum / (postSubsample * postSubsample));
            buf[pos++] = (short) (bsum / (postSubsample * postSubsample));
        }
    }
    log.debug("subsampled " + (System.currentTimeMillis() - startTime));

    // Restore LibRaw state to what it was before dcraw_process
    lrd.image.write(0, rawData, 0, rawImageSize);
    lrd.progress_flags = oldFlags;
    lrd.sizes.width = rawWidth;
    lrd.sizes.height = rawHeight;
    lrd.idata.filters = oldFilters;
    rawData = null;

    // closeRaw();

    DataBuffer db = new DataBufferUShort(buf, buf.length);
    SampleModel sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, scaledW,
            scaledH, 3, 3 * scaledW, new int[] { 0, 1, 2 });
    WritableRaster r = Raster.createWritableRaster(sampleModel, db, new Point(0, 0));
    log.debug("raster created " + (System.currentTimeMillis() - startTime));

    if (this.chanMultipliers == null) {
        chanMultipliers = cameraMultipliers.clone();
        calcCTemp();
    }

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    ColorModel targetCM = new ComponentColorModel(cs, new int[] { 16, 16, 16 }, false, false,
            Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
    rawImage = new TiledImage(new BufferedImage(targetCM, r, true, null), 256, 256);
    rawImage.setProperty("org.photovault.opname", "dcraw_data");

    if (preRotation.getJaiTransposeType() != null) {
        rawImage = TransposeDescriptor.create(rawImage, preRotation.getJaiTransposeType(), null);
        rawImage.setProperty("org.photovault.opname", "orientation_adjustment");
    }

    final float[] DEFAULT_KERNEL_1D = { 0.25f, 0.5f, 0.25f };
    ParameterBlock pb = new ParameterBlock();
    KernelJAI kernel = new KernelJAI(DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length,
            DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D, DEFAULT_KERNEL_1D);
    pb.add(kernel);
    BorderExtender extender = BorderExtender.createInstance(BorderExtender.BORDER_COPY);
    RenderingHints hints = JAI.getDefaultInstance().getRenderingHints();
    if (hints == null) {
        hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    } else {
        hints.put(JAI.KEY_BORDER_EXTENDER, extender);
    }

    RenderedOp filter = new RenderedOp("convolve", pb, hints);
    // javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

    // Add the subsampling operation.
    pb = new ParameterBlock();
    pb.addSource(filter);
    pb.add(new Float(0.5F)).add(new Float(0.5F));
    pb.add(new Float(0.0F)).add(new Float(0.0F));
    pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
    RenderedOp downSampler = new RenderedOp("scale", pb, null);
    // downSampler = javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

    RenderableOp rawImageRenderable = RenderableDescriptor.createRenderable(rawImage, downSampler, null, null,
            null, null, null);
    double colorCorrMat[][] = new double[][] { { colorCorr[0], 0.0, 0.0, 0.0 }, { 0.0, colorCorr[1], 0.0, 0.0 },
            { 0.0, 0.0, colorCorr[2], 0.0 } };

    RenderingHints nonCachedHints = new RenderingHints(JAI.KEY_TILE_CACHE, null);
    wbAdjustedRawImage = BandCombineDescriptor.createRenderable(rawImageRenderable, colorCorrMat,
            nonCachedHints);
    wbAdjustedRawImage.setProperty("org.photovault.opname", "wb_adjusted_image");

    //            reader.getImageMetadata( 0 );
    //            rawIsHalfSized = dcraw.ishalfSize();
    //
    //            createHistogram();
    //        } catch (FileNotFoundException ex) {
    //            ex.printStackTrace();
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        } catch (PhotovaultException ex) {
    //            ex.printStackTrace();
    //        }
    log.debug("image ready " + (System.currentTimeMillis() - startTime));

    if (autoExposeRequested) {
        doAutoExpose();
    }
    log.debug("exit: loadRawImage " + (System.currentTimeMillis() - startTime));

}

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

private void saveColorMatrix(float[][][] matrix, String filename, float min, float max) {
    byte[] buffer = new byte[size * size * 3];
    int i = 0;//from  ww  w .j  ava  2  s.c  o  m
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            buffer[i] = (byte) ((matrix[x][y][0] - min) * 255 / (max - min));
            i++;
            buffer[i] = (byte) ((matrix[x][y][1] - min) * 255 / (max - min));
            i++;
            buffer[i] = (byte) ((matrix[x][y][2] - min) * 255 / (max - min));
            i++;
        }
    }
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    int[] nBits = { 8, 8, 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 * 3);
    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);
    }
}