Example usage for javax.imageio ImageReader readRaster

List of usage examples for javax.imageio ImageReader readRaster

Introduction

In this page you can find the example usage for javax.imageio ImageReader readRaster.

Prototype

public Raster readRaster(int imageIndex, ImageReadParam param) throws IOException 

Source Link

Document

Returns a new Raster object containing the raw pixel data from the image stream, without any color conversion applied.

Usage

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

private BufferedImage getFallbackBufferedImage(ImageReader reader, int pageIndex, ImageReadParam param)
        throws IOException {
    //Work-around found at: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
    //There are some additional ideas there if someone wants to go further.

    // Try reading a Raster (no color conversion).
    Raster raster = reader.readRaster(pageIndex, param);

    // Arbitrarily select a BufferedImage type.
    int imageType;
    switch (raster.getNumBands()) {
    case 1:/*from w w  w  .  j ava2 s.c o  m*/
        imageType = BufferedImage.TYPE_BYTE_GRAY;
        break;
    case 3:
        imageType = BufferedImage.TYPE_3BYTE_BGR;
        break;
    case 4:
        imageType = BufferedImage.TYPE_4BYTE_ABGR;
        break;
    default:
        throw new UnsupportedOperationException();
    }

    // Create a BufferedImage.
    BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), imageType);

    // Set the image data.
    bi.getRaster().setRect(raster);
    return bi;
}

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

/**
 * Read a JPG image with CMYK ICC profile
 * @param imageByteArray/*from   w  ww  .j  av  a  2s . c om*/
 * @return The BufferedImage obj
 * @throws IOException
 * @throws ImageReadException
 */
public static BufferedImage readCMYK_JPG(byte[] imageByteArray) throws IOException, ImageReadException {

    colorType = COLOR_TYPE_RGB;
    hasAdobeMarker = false;

    InputStream in = new ByteArrayInputStream(imageByteArray);
    ImageInputStream stream = ImageIO.createImageInputStream(in);
    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);

    ImageReader reader = iter.next();
    reader.setInput(stream);

    BufferedImage image = null;
    ICC_Profile profile = null;

    colorType = COLOR_TYPE_CMYK;
    checkAdobeMarker(imageByteArray);
    profile = Imaging.getICCProfile(imageByteArray);

    WritableRaster raster = (WritableRaster) reader.readRaster(0, null);

    if (colorType == COLOR_TYPE_YCCK) {
        convertYcckToCmyk(raster);
    }
    if (hasAdobeMarker) {
        //convertInvertedColors(raster);
    }
    image = convertCmykToRgb(raster, profile);

    in.close();
    reader.dispose();
    return image;
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

/**
 * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are
 * converted, other images are left untouched.
 *
 * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either,
 * so we have to convert raster data to a JPG with RGB color space.
 *
 * The technique used in this method is due to Mark Stephens, and free for any use. See
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or
 * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html
 *
 * @param is the image data//  w w w. ja v  a2s  . co  m
 * @param colorModel the color model of the image
 * @return the RGB version of the supplied image
 */
public static InputStream convertToRGB(InputStream is, ColorModel colorModel)
        throws IOException, UnsupportedImageException {
    if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) {
        return is;
    }

    // Get an ImageReader.
    ImageInputStream input = ImageIO.createImageInputStream(is);

    try {
        Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
        if (readers == null || !readers.hasNext()) {
            throw new UnsupportedImageException("No ImageReaders found");
        }

        ImageReader reader = readers.next();
        reader.setInput(input);
        Raster raster = reader.readRaster(0, reader.getDefaultReadParam());

        int w = raster.getWidth();
        int h = raster.getHeight();
        byte[] rgb = new byte[w * h * 3];

        switch (colorModel) {
        case YCCK: {
            float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
            float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
            float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
            float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);

            for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];

                double val = y + 1.402 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y + 1.772 * (cb - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
            }
            break;
        }
        case CMYK: {
            int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
            int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
            int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
            int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);

            for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
                int c = 255 - C[i];
                int m = 255 - M[i];
                int y = 255 - Y[i];
                int k = 255 - K[i];
                float kk = k / 255f;

                rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
                rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
                rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
            }
            break;
        }
        }

        // from other image types we know InterleavedRaster's can be
        // manipulated by AffineTransformOp, so create one of those.
        raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3,
                new int[] { 0, 1, 2 }, null);

        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);
        BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", os);

        return new ByteArrayInputStream(os.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
        if (input != null) {
            input.close();
        }
    }
}

From source file:org.psystems.dicomweb.Dcm2Dcm.java

/**
 * Checks to see if the stream needs to be stripped down in bit depth.
 * Modifies meta to have a new dicom object if it is changing bit depth, and
 * updates various headers./*from   w w  w . j av a 2s  . c om*/
 */
protected LookupTable prepareBitStrip(DicomStreamMetaData meta, ImageReader reader) throws IOException {
    if (!destinationSyntax.uid().equals(UID.JPEGExtended24))
        return null;
    DicomObject ds = meta.getDicomObject();
    int stored = ds.getInt(Tag.BitsStored);
    if (stored < 13)
        return null;
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    WritableRaster r = (WritableRaster) reader.readRaster(0, null);
    int[] mm = VOIUtils.calcMinMax(ds, r);
    if (frames > 1) {
        r = (WritableRaster) reader.readRaster(frames - 1, null);
        int[] mm2 = VOIUtils.calcMinMax(ds, r);
        mm[0] = Math.min(mm[0], mm2[0]);
        mm[1] = Math.min(mm[1], mm2[1]);
    }
    if (frames > 2) {
        r = (WritableRaster) reader.readRaster(frames / 2 - 1, null);
        int[] mm2 = VOIUtils.calcMinMax(ds, r);
        mm[0] = Math.min(mm[0], mm2[0]);
        mm[1] = Math.min(mm[1], mm2[1]);
    }
    ds.putInt(Tag.SmallestImagePixelValue, VR.IS, mm[0]);
    ds.putInt(Tag.LargestImagePixelValue, VR.IS, mm[1]);
    int maxVal = mm[1];
    if (mm[0] < 0) {
        maxVal = Math.max(maxVal, 1 - mm[0]);
        maxVal *= 2;
    }
    int bits = 0;
    while (maxVal > 0) {
        bits++;
        maxVal >>= 1;
    }
    boolean signed = ds.getInt(Tag.PixelRepresentation) == 1;
    if (bits < 13 && mm[0] >= 0) {
        ds.putInt(Tag.BitsStored, VR.IS, bits);
        ds.putInt(Tag.HighBit, VR.IS, bits - 1);
        ds.putInt(Tag.PixelRepresentation, VR.IS, 0);
        return null;
    }
    ds.putInt(Tag.BitsStored, VR.IS, 12);
    ds.putInt(Tag.HighBit, VR.IS, 11);
    // Number of entries required
    int entries = mm[1] - mm[0] + 1;
    short[] slut = new short[entries];
    int range = entries - 1;
    for (int i = 0; i < entries; i++) {
        slut[i] = (short) ((4095 * i) / range);
    }
    if (signed) {
        ds.putInt(Tag.PixelRepresentation, VR.IS, 0);
    }
    LookupTable lut = new ShortLookupTable(stored, signed, -mm[0], 12, slut);
    return lut;
}

From source file:org.psystems.dicomweb.Dcm2Dcm.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*from  ww  w .  ja v  a 2s.co  m*/
public void recodeImages(File src, File dest) throws IOException {

    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}

From source file:org.psystems.dicomweb.Dcm2DcmCopy.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*from  www  .  j a  v a2 s  .  c  om*/
public void recodeImages(File src, File dest) throws IOException {
    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}