Example usage for java.awt.image ColorModel hasAlpha

List of usage examples for java.awt.image ColorModel hasAlpha

Introduction

In this page you can find the example usage for java.awt.image ColorModel hasAlpha.

Prototype

public final boolean hasAlpha() 

Source Link

Document

Returns whether or not alpha is supported in this ColorModel .

Usage

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

/** {@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 {/*from   w  w w . j a v a  2s  .  co m*/
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    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;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.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);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // 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 == null || 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);
    }
}

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

private int getAlphaBandIndex(GridCoverage2D coverage) {
    final ColorModel cm = coverage.getRenderedImage().getColorModel();
    if (!cm.hasAlpha() || cm.getNumComponents() == cm.getNumColorComponents()) {
        throw new IllegalArgumentException(
                "The source coverage does not have an alpha band, cannot extract an alpha band");
    }/*  w ww .  j a  v a2 s.  c om*/
    // the alpha band is always the last (see ComponentColorModel.getAlphaRaster or the getAlpha(object) code
    if (cm.getNumColorComponents() == 1) {
        // gray-alpha
        return 1;
    } else {
        // rgba/argb
        return 3;
    }
}

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

/**
 * Checks if a reader added a alpha channel on the fly as a result of a read parameter. We want to preserve
 * this alpha channel because the user never got a chance to select its presence in the output (e.g. 
 * footprint management in mosaic)/*  ww  w.ja va 2  s.  co m*/
 * @param coverage
 * @param reader
 * @return
 * @throws IOException 
 */
private boolean hasDynamicAlpha(GridCoverage2D coverage, GridCoverage2DReader reader) throws IOException {
    // check if we have an alpha band in the coverage to stat with
    if (coverage == null) {
        return false;
    }
    ColorModel dynamicCm = coverage.getRenderedImage().getColorModel();
    if (!dynamicCm.hasAlpha() || !hasAlphaBand(dynamicCm)) {
        return false;
    }

    // check if we did not have one in the original layout
    ImageLayout readerLayout = reader.getImageLayout();
    if (readerLayout == null) {
        return false;
    }
    ColorModel nativeCm = readerLayout.getColorModel(null);
    if (nativeCm == null || nativeCm.hasAlpha()) {
        return false;
    }

    // the coverage has an alpha band, but the original reader does not advertise one? 
    return !hasAlphaBand(nativeCm);

}

From source file:org.geoserver.wps.gs.raster.algebra.JiffleScriptProcessTest.java

@Test
public void testOnAllBands() throws Exception {

    if (testCoverage3 != null) {
        // Script selection
        String script = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_PATH));
        // Process calculation
        List<String> scripts = new ArrayList<String>(1);
        scripts.add(script);// ww w  . j a v  a  2s .c o m
        GridCoverage2D finalCoverage = process2.execute(testCoverage3, scripts);
        // Check the result
        assertNotNull(finalCoverage);

        RenderedImage finalImage = finalCoverage.getRenderedImage();
        // Check on the number of bands
        int numBandsOut = finalImage.getSampleModel().getNumBands();

        int numBandsIn = testCoverage3.getRenderedImage().getSampleModel().getNumBands();

        ColorModel cm = testCoverage3.getRenderedImage().getColorModel();

        if (cm.hasAlpha() && !cm.isAlphaPremultiplied()) {
            numBandsIn--;
        }

        assertEquals(numBandsIn, numBandsOut);

        PlanarImage.wrapRenderedImage(finalImage).getTiles();

        int[] values = new int[] { MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_0 };

        checkExecution(finalImage, values, testCoverage3);

        finalCoverage.dispose(true);
        if (finalImage instanceof RenderedOp) {
            ((RenderedOp) finalImage).dispose();
        }
    } else {
        LOGGER.log(Level.WARNING, "\nTest5: file " + IMAGE_NAME_3
                + " not found in geoserver-enterprise/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/raster/algebra");
    }
}

From source file:org.geoserver.wps.gs.raster.algebra.JiffleScriptProcessTest.java

@Test
public void testOnAllBandsMultiScripts() throws Exception {

    if (testCoverage3 != null) {
        // Script1 selection
        String script = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_PATH));
        // Script2 selection
        String script2 = FileUtils.readFileToString(new File(JIFFLE_SCRIPT_2_PATH));
        // Process calculation
        List<String> scripts = new ArrayList<String>(1);
        scripts.add(script);/*from w ww.  ja v  a  2  s  . co m*/
        scripts.add(script2);
        scripts.add(script2);
        GridCoverage2D finalCoverage = process2.execute(testCoverage3, scripts);
        // Check the result
        assertNotNull(finalCoverage);

        RenderedImage finalImage = finalCoverage.getRenderedImage();
        // Check on the number of bands
        int numBandsOut = finalImage.getSampleModel().getNumBands();

        int numBandsIn = testCoverage3.getRenderedImage().getSampleModel().getNumBands();

        ColorModel cm = testCoverage3.getRenderedImage().getColorModel();

        if (cm != null && cm instanceof ComponentColorModel && cm.hasAlpha() && !cm.isAlphaPremultiplied()) {
            numBandsIn--;
        }

        assertEquals(numBandsIn, numBandsOut);

        PlanarImage.wrapRenderedImage(finalImage).getTiles();

        int[] values = new int[] { MORE_THAN_ZERO_BAND_0, MORE_THAN_ZERO_BAND_1, MORE_THAN_ZERO_BAND_1 };

        checkExecution(finalImage, values, testCoverage3);

        finalCoverage.dispose(true);
        if (finalImage instanceof RenderedOp) {
            ((RenderedOp) finalImage).dispose();
        }
    } else {
        LOGGER.log(Level.WARNING, "\nTest6: file " + IMAGE_NAME_3
                + " not found in geoserver-enterprise/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/raster/algebra");
    }
}

From source file:org.yccheok.jstock.gui.Utils.java

private static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }//from w  w  w .j a v a  2s .  c  om

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();

    return cm.hasAlpha();
}

From source file:ro.nextreports.designer.util.ImageUtil.java

private static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }//  w w w. j  a va2  s . c o m

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
}

From source file:util.ImgJaiTool.java

protected static RenderedOp removeAlphaTransparency(RenderedOp image) {
    ColorModel cm = image.getColorModel();
    if (cm.hasAlpha() || cm.getNumColorComponents() == 4) {
        if (cm instanceof IndexColorModel) {
            // band combine doesn't work on IndexColorModel
            // http://java.sun.com/products/java-media/jai/jai-bugs-1_0_2.html
            IndexColorModel icm = (IndexColorModel) cm;
            byte[][] data = new byte[3][icm.getMapSize()];
            icm.getReds(data[0]);//from w  ww.  ja  v  a 2 s  .  c  om
            icm.getGreens(data[1]);
            icm.getBlues(data[2]);
            LookupTableJAI lut = new LookupTableJAI(data);
            image = JAI.create("lookup", image, lut);
        } else {
            image = BandCombineDescriptor.create(image, strip_alpha_matrix, null);
        }
    }
    return image;
}