Example usage for java.awt.image ColorModel getTransparency

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

Introduction

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

Prototype

public int getTransparency() 

Source Link

Document

Returns the transparency.

Usage

From source file:org.apache.fop.render.pdf.ImageRenderedAdapter.java

/** {@inheritDoc} */
@Override/*from w  w w.jav a2  s .c om*/
public PDFColor getTransparentColor() {
    ColorModel cm = getEffectiveColorModel();
    if (cm instanceof IndexColorModel) {
        IndexColorModel icm = (IndexColorModel) cm;
        if (cm.getTransparency() == IndexColorModel.TRANSLUCENT) {
            int transPixel = icm.getTransparentPixel();
            return new PDFColor(icm.getRed(transPixel), icm.getGreen(transPixel), icm.getBlue(transPixel));
        }
    }
    return new PDFColor(getImage().getTransparentColor());
}

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  .  ja v a2 s .  c  om
        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.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testTransparentPaletteOpaqueOutput() throws Exception {
    String url = "wms?LAYERS=" + getLayerId(MockData.TASMANIA_DEM) + "&styles=demTranslucent&"
            + "FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1" + "&REQUEST=GetMap&SRS=EPSG%3A4326"
            + "&BBOX=145,-43,146,-41&WIDTH=100&HEIGHT=200&bgcolor=0xFF0000";
    BufferedImage bi = getAsImage(url, "image/png");

    ColorModel cm = bi.getColorModel();
    assertTrue(cm instanceof IndexColorModel);
    assertEquals(Transparency.OPAQUE, cm.getTransparency());

    // grab a pixel in the low left corner, should be red (BG color)
    int[] pixel = new int[1];
    bi.getRaster().getPixel(4, 196, pixel);
    int[] color = new int[3];
    cm.getComponents(pixel[0], color, 0);
    assertEquals(255, color[0]);/* w  ww.  j  a  v  a  2s. com*/
    assertEquals(0, color[1]);
    assertEquals(0, color[2]);

    // a pixel high enough to be solid, should be fully green
    bi.getRaster().getPixel(56, 49, pixel);
    cm.getComponents(pixel[0], color, 0);
    assertEquals(0, color[0]);
    assertEquals(255, color[1]);
    assertEquals(0, color[2]);
}

From source file:org.geoserver.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testTransparentPaletteTransparentOutput() throws Exception {
    String url = "wms?LAYERS=" + getLayerId(MockData.TASMANIA_DEM) + "&styles=demTranslucent&"
            + "FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1" + "&REQUEST=GetMap&SRS=EPSG%3A4326"
            + "&BBOX=145,-43,146,-41&WIDTH=100&HEIGHT=200&transparent=true";
    BufferedImage bi = getAsImage(url, "image/png");

    ColorModel cm = bi.getColorModel();
    assertTrue(cm instanceof IndexColorModel);
    assertEquals(Transparency.TRANSLUCENT, cm.getTransparency());

    // grab a pixel in the low left corner, should be transparent
    int[] pixel = new int[1];
    bi.getRaster().getPixel(4, 196, pixel);
    int[] color = new int[4];
    cm.getComponents(pixel[0], color, 0);
    assertEquals(0, color[3]);/*from  w ww .j  a  va  2s  .  co  m*/

    // a pixel high enough to be solid, should be solid green
    bi.getRaster().getPixel(56, 49, pixel);
    cm.getComponents(pixel[0], color, 0);
    assertEquals(0, color[0]);
    assertEquals(255, color[1]);
    assertEquals(0, color[2]);
    assertEquals(255, color[3]);
}

From source file:org.geoserver.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testTransparentPaletteTransparentOutputPng8() throws Exception {
    String url = "wms?LAYERS=" + getLayerId(MockData.TASMANIA_DEM) + "&styles=demTranslucent&"
            + "FORMAT=image%2Fpng8&SERVICE=WMS&VERSION=1.1.1" + "&REQUEST=GetMap&SRS=EPSG%3A4326"
            + "&BBOX=145,-43,146,-41&WIDTH=100&HEIGHT=200&transparent=true";
    BufferedImage bi = getAsImage(url, "image/png; mode=8bit");

    ColorModel cm = bi.getColorModel();
    assertTrue(cm instanceof IndexColorModel);
    assertEquals(Transparency.TRANSLUCENT, cm.getTransparency());

    // grab a pixel in the low left corner, should be transparent
    int[] pixel = new int[1];
    bi.getRaster().getPixel(4, 196, pixel);
    int[] color = new int[4];
    cm.getComponents(pixel[0], color, 0);
    assertEquals(0, color[3]);/*from w  w  w. j a  v  a2s .c om*/

    // a pixel high enough to be solid, should be solid green
    bi.getRaster().getPixel(56, 49, pixel);
    cm.getComponents(pixel[0], color, 0);
    assertEquals(0, color[0]);
    assertEquals(255, color[1]);
    assertEquals(0, color[2]);
    assertEquals(255, color[3]);
}

From source file:org.geoserver.wps.gs.GeorectifyCoverage.java

@DescribeResults({
        @DescribeResult(name = "result", description = "Georectified raster", type = GridCoverage2D.class),
        @DescribeResult(name = "path", description = "Pathname of the generated raster on the server", type = String.class) })
public Map<String, Object> execute(
        @DescribeParameter(name = "data", description = "Input raster") GridCoverage2D coverage,
        @DescribeParameter(name = "gcp", description = "List of Ground control points.  Points are specified as [x,y] or [x,y,z].") String gcps,
        @DescribeParameter(name = "bbox", description = "Bounding box for output", min = 0) Envelope bbox,
        @DescribeParameter(name = "targetCRS", description = "Coordinate reference system to use for the output raster") CoordinateReferenceSystem crs,
        @DescribeParameter(name = "width", description = "Width of output raster in pixels", min = 0) Integer width,
        @DescribeParameter(name = "height", description = "Height of output raster in pixels", min = 0) Integer height,
        @DescribeParameter(name = "warpOrder", min = 0, description = "Order of the warping polynomial (1 to 3)") Integer warpOrder,
        @DescribeParameter(name = "transparent", min = 0, description = "Force output to have transparent background") Boolean transparent,
        @DescribeParameter(name = "store", min = 0, description = "Indicates whether to keep the output file after processing") Boolean store,
        @DescribeParameter(name = "outputPath", min = 0, description = "Pathname where the output file is stored") String outputPath)
        throws IOException {

    GeoTiffReader reader = null;//from ww  w .  j a va 2 s .  c  o  m
    List<File> removeFiles = new ArrayList<File>();
    String location = null;
    try {
        File tempFolder = config.getTempFolder();
        File loggingFolder = config.getLoggingFolder();

        // do we have to add the alpha channel?
        boolean forceTransparent = false;
        if (transparent == null) {
            transparent = true;
        }
        ColorModel cm = coverage.getRenderedImage().getColorModel();
        if (cm.getTransparency() == Transparency.OPAQUE && transparent) {
            forceTransparent = true;
        }

        // //
        //
        // STEP 1: Getting the dataset to be georectified
        //
        // //
        final Object fileSource = coverage.getProperty(GridCoverage2DReader.FILE_SOURCE_PROPERTY);
        if (fileSource != null && fileSource instanceof String) {
            location = (String) fileSource;
        }
        if (location == null) {
            RenderedImage image = coverage.getRenderedImage();
            if (forceTransparent) {
                ImageWorker iw = new ImageWorker(image);
                iw.forceComponentColorModel();
                final ImageLayout tempLayout = new ImageLayout(image);
                tempLayout.unsetValid(ImageLayout.COLOR_MODEL_MASK).unsetValid(ImageLayout.SAMPLE_MODEL_MASK);
                RenderedImage alpha = ConstantDescriptor.create(Float.valueOf(image.getWidth()),
                        Float.valueOf(image.getHeight()), new Byte[] { Byte.valueOf((byte) 255) },
                        new RenderingHints(JAI.KEY_IMAGE_LAYOUT, tempLayout));
                iw.addBand(alpha, false);
                image = iw.getRenderedImage();
                cm = image.getColorModel();
            }
            File storedImageFile = storeImage(image, tempFolder);
            location = storedImageFile.getAbsolutePath();
            removeFiles.add(storedImageFile);
        }

        // //
        //
        // STEP 2: Adding Ground Control Points
        //
        // //
        final int gcpNum[] = new int[1];
        final String gcp = parseGcps(gcps, gcpNum);
        File vrtFile = addGroundControlPoints(location, gcp, config.getGdalTranslateParameters());
        if (vrtFile == null || !vrtFile.exists() || !vrtFile.canRead()) {
            throw new IOException("Unable to get a valid file with attached Ground Control Points");
        }
        removeFiles.add(vrtFile);

        // //
        //
        // STEP 3: Warping
        //
        // //
        File warpedFile = warpFile(vrtFile, bbox, crs, width, height, warpOrder, tempFolder, loggingFolder,
                config.getExecutionTimeout(), config.getGdalWarpingParameters());
        if (warpedFile == null || !warpedFile.exists() || !warpedFile.canRead()) {
            throw new IOException("Unable to get a valid georectified file");
        }

        boolean expand = false;
        if (cm instanceof IndexColorModel) {
            expand = true;
        } else if (cm instanceof ComponentColorModel && cm.getNumComponents() == 1
                && cm.getComponentSize()[0] == 1) {
            expand = true;
        }
        if (expand) {
            removeFiles.add(warpedFile);
            warpedFile = expandRgba(warpedFile.getAbsolutePath());
        }

        // if we have the output path move the final file there
        if (Boolean.TRUE.equals(store) && outputPath != null) {
            File output = new File(outputPath);
            if (output.exists()) {
                if (!output.delete()) {
                    throw new WPSException("Output file " + outputPath + " exists but cannot be overwritten");
                }
            } else {
                File parent = output.getParentFile();
                if (!parent.exists()) {
                    if (!parent.mkdirs()) {
                        throw new WPSException("Output file parent directory " + parent.getAbsolutePath()
                                + " does not exist and cannot be created");
                    }
                }
            }
            if (!warpedFile.renameTo(output)) {
                throw new WPSException("Could not move " + warpedFile.getAbsolutePath() + " to " + outputPath
                        + ", it's likely a permission issue");
            }
            warpedFile = output;
        }

        // mark the output file for deletion at the end of request
        if (resourceManager != null && !Boolean.TRUE.equals(store)) {
            resourceManager.addResource(new WPSFileResource(warpedFile));
        }

        // //
        //
        // FINAL STEP: Returning the warped gridcoverage
        //
        // //
        reader = new GeoTiffReader(warpedFile);
        GridCoverage2D cov = addLocationProperty(reader.read(null), warpedFile);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("result", cov);
        result.put("path", warpedFile.getAbsolutePath());
        return result;
    } finally {
        if (reader != null) {
            try {
                reader.dispose();
            } catch (Throwable t) {
                // Does nothing
            }
        }

        for (File file : removeFiles) {
            deleteFile(file);
        }
    }
}