Package org.geotools.image

Examples of org.geotools.image.ImageWorker


        PlanarImage[] alphaChannels = null;

        //
        // IndexColorModel
        //
        final ImageWorker worker = new ImageWorker(image);
        final int transparencyType=cm.getTransparency();
       
        // in case of index color model we try to preserve it, so that output
        // formats that can work with it can enjoy its extra compactness
        if (cm instanceof IndexColorModel) {
            IndexColorModel icm = (IndexColorModel) cm;
            // try to find the index that matches the requested background color
            final int bgColorIndex;
            if(transparent) {
                bgColorIndex = icm.getTransparentPixel();
            } else {
                if(icm.hasAlpha() && icm.isAlphaPremultiplied()) {
                    // uncommon case that we don't have the code to handle directly
                    bgColorIndex = -1;
                } else {
                    if(icm.getTransparency() != Transparency.OPAQUE) {
                        // we have a translucent image, so the bg color needs to be merged into
                        // the palette
                        icm = ColorUtilities.applyBackgroundColor(icm, bgColor);
                        cm = icm;
                        ImageLayout ilColorModel = new ImageLayout(image);
                        ilColorModel.setColorModel(icm);
                        RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ilColorModel);
                        image = FormatDescriptor.create(image, image.getSampleModel().getDataType(), hints);
                        worker.setImage(image);
                    }
                    bgColorIndex = ColorUtilities.findColorIndex(bgColor, icm);
                }
            }
           
            // we did not find the background color, well we have to expand to RGB and then tell Mosaic to use the RGB(A) color as the
            // background
            if (bgColorIndex == -1) {
                // we need to expand the image to RGB
                image = worker.forceComponentColorModel().getRenderedImage();
                if(transparent) {
                    image = addAlphaChannel(image);
                    worker.setImage(image);
                }
                bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(),
                        transparent ? 0 : 255 };
                cm = image.getColorModel();
            } else {
              // we found the background color in the original image palette therefore we set its index as the bkg value.
              // The final Mosaic will use the IndexColorModel of this image anywa, therefore all we need to do is to force
              // the background to point to the right color in the palette
                bgValues = new double[] { bgColorIndex };
            }
           
            // collect alpha channels if we have them in order to reuse them later on for mosaic operation
            if (cm.hasAlpha() && bgColorIndex == -1) {
                worker.forceComponentColorModel();
                final RenderedImage alpha = worker.retainLastBand().getRenderedImage();
                alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
            }
        }
       
        //
        // ComponentColorModel
        //
       
        // in case of component color model
        if (cm instanceof ComponentColorModel) {

            // convert to RGB if necessary
            ComponentColorModel ccm = (ComponentColorModel) cm;
            boolean hasAlpha = cm.hasAlpha();

            // if we have a grayscale image see if we have to expand to RGB
            if (ccm.getNumColorComponents() == 1) {
                if((!isLevelOfGray(bgColor) && !transparent) || (ccm.getTransferType() == DataBuffer.TYPE_DOUBLE ||
                        ccm.getTransferType() == DataBuffer.TYPE_FLOAT
                        || ccm.getTransferType() == DataBuffer.TYPE_UNDEFINED)) {
                    // expand to RGB, this is not a case we can optimize
                    final ImageWorker iw = new ImageWorker(image);
                    if (hasAlpha) {
                        final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                        // get first band
                        final RenderedImage gray = new ImageWorker(image).retainFirstBand()
                                .getRenderedImage();
                        image = new ImageWorker(gray).bandMerge(3).addBand(alpha, false)
                                .forceComponentColorModel().forceColorSpaceRGB().getRenderedImage();
                    } else {
                        image = iw.bandMerge(3).forceComponentColorModel().forceColorSpaceRGB()
                                .getRenderedImage();
                    }
                } else if(!hasAlpha) {
                    // no transparency in the original data, so no need to expand to RGB
                    if(transparent) {
                        // we need to expand the image with an alpha channel
                        image = addAlphaChannel(image);
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 0 };
                    } else {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm) };
                    }
                } else {
                    // extract the alpha channel
                    final ImageWorker iw = new ImageWorker(image);
                    final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                    alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
                   
                    if (transparent) {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 0 };
                    } else {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 255 };
                    }
                }

                // get back the ColorModel
                cm = image.getColorModel();
                ccm = (ComponentColorModel) cm;
                hasAlpha = cm.hasAlpha();
            }

            if(bgValues == null) {
                if (hasAlpha) {
                    // get alpha
                  final ImageWorker iw = new ImageWorker(image);
                    final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                    alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
   
                    if (transparent) {
                        bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(),
                                bgColor.getBlue(), 0 };
                    } else {
                        bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(),
                                bgColor.getBlue(), 255 };
                    }
                } else {
                    if (transparent) {
                        image = addAlphaChannel(image);
                        // this will work fine for all situation where the color components are <= 3
                        // e.g., one band rasters with no colormap will have only one usually
                        bgValues = new double[] { 0, 0, 0, 0 };
                    } else {
                        // TODO: handle the case where the component color model is not RGB
                        // We cannot use ImageWorker as is because it basically seems to assume
                        // component -> 3 band in forceComponentColorModel()
                        // but I guess we'll need to turn the image into a 3 band RGB one.
                        bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(),
                                bgColor.getBlue() };
                    }
                }
            }
        }
       
        //
        // If we need to add a collar use mosaic or if we need to blend/apply a bkg color
        if(!(imageBounds.contains(mapRasterArea) || imageBounds.equals(mapRasterArea))||transparencyType!=Transparency.OPAQUE) {
            ROI[] rois = new ROI[] { new ROIShape(imageBounds) };

            // build the transparency thresholds
            double[][] thresholds = new double[][] { { ColorUtilities.getThreshold(image
                    .getSampleModel().getDataType()) } };
            // apply the mosaic
            image = MosaicDescriptor.create(new RenderedImage[] { image },
                    alphaChannels != null && transparencyType==Transparency.TRANSLUCENT ? MosaicDescriptor.MOSAIC_TYPE_BLEND: MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
                    alphaChannels, rois, thresholds, bgValues, new RenderingHints(
                            JAI.KEY_IMAGE_LAYOUT, layout));
        } else {
            // Check if we need to crop a subset of the produced image, else return it right away
            if (imageBounds.contains(mapRasterArea) && !imageBounds.equals(mapRasterArea)) { // the produced image does not need a final mosaicking operation but a crop!
                ImageWorker iw = new ImageWorker(image);
                iw.crop(0, 0, mapWidth, mapHeight);
                image = iw.getRenderedImage();
            }
        }
       
        return image;
    }
View Full Code Here


                image = forceIndexed8Bitmask(image, null);
            }
        } else {
            if (!(image.getColorModel() instanceof IndexColorModel)) {
                // try to force a RGBA setup
                image = new ImageWorker(image).rescaleToBytes().forceComponentColorModel()
                        .getRenderedImage();
                ColorIndexer indexer = null;
               
                // user provided palette?
                if (mapContent.getPalette() != null) {
View Full Code Here

                // The image is indexed on 8 bits and the color model is
                // Translucent, we have to perform some color operations in
                // order to convert it to bitmask.
                //
                // //
                image = new ImageWorker(originalImage).forceBitmaskIndexColorModel().getRenderedImage();
                if(DEBUG){
                  writeRenderedImage(image, "indexed8translucent");
                }
            }
        } else {
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.finer("Image has generic color model and/or type");
            }         
            // /////////////////////////////////////////////////////////////////
            //
            // NOT IndexColorModel and DataBuffer.TYPE_BYTE
            //
            // ///
            //
            // We got an image that needs to be converted.
            //
            // /////////////////////////////////////////////////////////////////
          image = new ImageWorker(originalImage).rescaleToBytes().getRenderedImage();
            if (invColorMap != null) {
                if (LOGGER.isLoggable(Level.FINER)) {
                    LOGGER.finer("We have an invColorMap");
               
                // make me parametric which means make me work with other image
                // types
                image = invColorMap.filterRenderedImage(image);
                if(DEBUG){
                  writeRenderedImage(image, "invColorMap");
                }               
            } else {
                if (LOGGER.isLoggable(Level.FINER)) {
                    LOGGER.finer("We do not have an invColorMap");
                }               
                // //
                //
                // We do not have a paletteInverter, let's create a palette that
                // is as good as possible.
                //
                // //
                // make sure we start from a componentcolormodel.
                if (LOGGER.isLoggable(Level.FINER)) {
                    LOGGER.finer("Making sure we start from a componentcolormodel");
                }               
                image = new ImageWorker(image).forceComponentColorModel().getRenderedImage();
                if(DEBUG){
                  writeRenderedImage(image, "forceComponentColorModel");
                }                 

                // //
View Full Code Here

        PNGWriter writer = new PNGWriter();
        // Check if a Scanline is supported by the writer
        boolean isScanlineSupported = writer.isScanlineSupported(image);
        // If it is not supported, then the image is rescaled to bytes
        if(!isScanlineSupported){
            image = new ImageWorker(image).rescaleToBytes().forceComponentColorModel().getRenderedImage();          
        }
       
        RenderedImage output = null;
        // Image writing
        try {
View Full Code Here

            finalEnvelope.setCoordinateReferenceSystem(sourceCoverage.getCoordinateReferenceSystem());
            assertEquals(50, targetCoverage.getGridGeometry().getGridRange().getSpan(0));
            assertEquals(50, targetCoverage.getGridGeometry().getGridRange().getSpan(1));
           
            // get extrema
            assertEquals(29.0,new ImageWorker(targetCoverage.getRenderedImage()).getMaximums()[0]);
        } finally {
            try{
                readerTarget.dispose();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
            try{
                scheduleForCleaning(targetCoverage);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
            try{
                scheduleForCleaning(sourceCoverage);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
        }
       

        try {

            // source
            sourceCoverage=(GridCoverage2D) this.getCatalog().getCoverageByName("BlueMarble").getGridCoverageReader(null, null).read(null);
            final Envelope2D sourceEnvelope = sourceCoverage.getEnvelope2D();
           
            // upsample
            MockHttpServletResponse response = getAsServletResponse("wcs?request=GetCoverage&service=WCS&version=2.0.1" +
                    "&coverageId=wcs__BlueMarble&&Format=image/tiff&SCALESIZE=http://www.opengis.net/def/axis/OGC/1/i(1000)," +
                            "http://www.opengis.net/def/axis/OGC/1/j(1000)&" +
                            "&subset=http://www.opengis.net/def/axis/OGC/0/Long(" +sourceEnvelope.x+","+(sourceEnvelope.x+sourceEnvelope.width/2)+")"+
                            "&subset=http://www.opengis.net/def/axis/OGC/0/Lat(" +sourceEnvelope.y+","+(sourceEnvelope.y+sourceEnvelope.height/2)+")");
           
            assertEquals("image/tiff", response.getContentType());
            byte[] tiffContents = getBinary(response);
            File file = File.createTempFile("bm_gtiff", "bm_gtiff.tiff", new File("./target"));
            FileUtils.writeByteArrayToFile(file, tiffContents);
           
            // check we can read it as a TIFF and it is similare to the origina one
            readerTarget = new GeoTiffReader(file);
           
            targetCoverage = readerTarget.read(null);
            sourceCoverage=(GridCoverage2D) this.getCatalog().getCoverageByName("BlueMarble").getGridCoverageReader(null, null).read(null);
           
            // checks
            assertEquals(sourceCoverage.getCoordinateReferenceSystem(), targetCoverage.getCoordinateReferenceSystem());
            assertEquals(1000, targetCoverage.getGridGeometry().getGridRange().getSpan(0));
            assertEquals(1000, targetCoverage.getGridGeometry().getGridRange().getSpan(1));

            final GeneralEnvelope finalEnvelope= new GeneralEnvelope(
                    new double[]{sourceEnvelope.x,sourceEnvelope.y},
                    new double[]{sourceEnvelope.x+sourceEnvelope.width*2,sourceEnvelope.y+sourceEnvelope.height*2});
            finalEnvelope.setCoordinateReferenceSystem(sourceCoverage.getCoordinateReferenceSystem());
           
            // get extrema
            assertEquals(29.0,new ImageWorker(targetCoverage.getRenderedImage()).getMaximums()[0]);           
        } finally {
            try{
                readerTarget.dispose();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
View Full Code Here

            finalEnvelope.setCoordinateReferenceSystem(sourceCoverage.getCoordinateReferenceSystem());
            assertEquals(100, targetCoverage.getGridGeometry().getGridRange().getSpan(0));
            assertEquals(100, targetCoverage.getGridGeometry().getGridRange().getSpan(1));
           
            // get extrema
            assertEquals(29.0,new ImageWorker(targetCoverage.getRenderedImage()).getMaximums()[0]);
        } finally {
            try{
                readerTarget.dispose();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
            try{
                scheduleForCleaning(targetCoverage);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
            try{
                scheduleForCleaning(sourceCoverage);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
            }
        }
       

        try {

            // source
            sourceCoverage=(GridCoverage2D) this.getCatalog().getCoverageByName("BlueMarble").getGridCoverageReader(null, null).read(null);
            final Envelope2D sourceEnvelope = sourceCoverage.getEnvelope2D();
           
            // upsample
            MockHttpServletResponse response = getAsServletResponse("wcs?request=GetCoverage&service=WCS&version=2.0.1" +
                    "&coverageId=wcs__BlueMarble&&Format=image/tiff&SCALEEXTENT=http://www.opengis.net/def/axis/OGC/1/i(100,1099)," +
                        "http://www.opengis.net/def/axis/OGC/1/j(100,1099)" +
                        "&subset=http://www.opengis.net/def/axis/OGC/0/Long(" +sourceEnvelope.x+","+(sourceEnvelope.x+sourceEnvelope.width/2)+")"+
                            "&subset=http://www.opengis.net/def/axis/OGC/0/Lat(" +sourceEnvelope.y+","+(sourceEnvelope.y+sourceEnvelope.height/2)+")");
           
            assertEquals("image/tiff", response.getContentType());
            byte[] tiffContents = getBinary(response);
            File file = File.createTempFile("bm_gtiff", "bm_gtiff.tiff", new File("./target"));
            FileUtils.writeByteArrayToFile(file, tiffContents);
           
            // check we can read it as a TIFF and it is similare to the origina one
            readerTarget = new GeoTiffReader(file);
           
            targetCoverage = readerTarget.read(null);
            sourceCoverage=(GridCoverage2D) this.getCatalog().getCoverageByName("BlueMarble").getGridCoverageReader(null, null).read(null);
           
            // checks
            assertEquals(sourceCoverage.getCoordinateReferenceSystem(), targetCoverage.getCoordinateReferenceSystem());
            final GeneralEnvelope finalEnvelope= new GeneralEnvelope(
                    new double[]{sourceEnvelope.x,sourceEnvelope.y},
                    new double[]{sourceEnvelope.x+sourceEnvelope.width/2,sourceEnvelope.y+sourceEnvelope.height/2});
            finalEnvelope.setCoordinateReferenceSystem(sourceCoverage.getCoordinateReferenceSystem());
            assertEquals(1000, targetCoverage.getGridGeometry().getGridRange().getSpan(0));
            assertEquals(1000, targetCoverage.getGridGeometry().getGridRange().getSpan(1));
           
            // geotiff encoding looses the min values and pushes to zero
            assertEquals(0, targetCoverage.getGridGeometry().getGridRange().getLow(0));
            assertEquals(0, targetCoverage.getGridGeometry().getGridRange().getLow(1));
            assertEquals(999, targetCoverage.getGridGeometry().getGridRange().getHigh(0));
            assertEquals(999, targetCoverage.getGridGeometry().getGridRange().getHigh(1));
           
            // get extrema
            assertEquals(29.0,new ImageWorker(targetCoverage.getRenderedImage()).getMaximums()[0]);
        } finally {
            try{
                readerTarget.dispose();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,e.getLocalizedMessage(),e);
View Full Code Here

        PlanarImage[] alphaChannels = null;

        //
        // IndexColorModel
        //
        final ImageWorker worker = new ImageWorker(image);
        final int transparencyType=cm.getTransparency();
       
        // in case of index color model we try to preserve it, so that output
        // formats that can work with it can enjoy its extra compactness
        if (cm instanceof IndexColorModel) {
            final IndexColorModel icm = (IndexColorModel) cm;
            // try to find the index that matches the requested background color
            final int bgColorIndex;
            if(transparent) {
                bgColorIndex = icm.getTransparentPixel();
            } else {
                bgColorIndex = ColorUtilities.findColorIndex(bgColor, icm);
            }
           
            //we did not find the background color, well we have to expand to RGB and then tell Mosaic to use the RGB(A) color as the
            // background
            if (bgColorIndex == -1) {
                // we need to expand the image to RGB
                image = worker.forceComponentColorModel().getRenderedImage();
                if(transparent) {
                    image = addAlphaChannel(image);
                    worker.setImage(image);
                }
                bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(),
                        transparent ? 0 : 255 };
                cm = image.getColorModel();
            } else {
              // we found the background color in the original image palette therefore we set its index as the bkg value.
              // The final Mosaic will use the IndexColorModel of this image anywa, therefore all we need to do is to force
              // the background to point to the right color in the palettte
                bgValues = new double[] { bgColorIndex };
            }
           
            //collect alpha channels if we have them in order to reuse them later on for mosaic operation
            if (cm.hasAlpha()) {
                worker.forceComponentColorModel();
                final RenderedImage alpha =worker.retainLastBand().getRenderedImage();
                alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
            }
        }
       
        //
        // ComponentColorModel
        //
       
        // in case of component color model
        if (cm instanceof ComponentColorModel) {

            // convert to RGB if necessary
            ComponentColorModel ccm = (ComponentColorModel) cm;
            boolean hasAlpha = cm.hasAlpha();

            // if we have a grayscale image see if we have to expand to RGB
            if (ccm.getNumColorComponents() == 1) {
                if((!isLevelOfGray(bgColor) && !transparent) || (ccm.getTransferType() == DataBuffer.TYPE_DOUBLE ||
                        ccm.getTransferType() == DataBuffer.TYPE_FLOAT
                        || ccm.getTransferType() == DataBuffer.TYPE_UNDEFINED)) {
                    // expand to RGB, this is not a case we can optimize
                    final ImageWorker iw = new ImageWorker(image);
                    if (hasAlpha) {
                        final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                        // get first band
                        final RenderedImage gray = new ImageWorker(image).retainFirstBand()
                                .getRenderedImage();
                        image = new ImageWorker(gray).bandMerge(3).addBand(alpha, false)
                                .forceComponentColorModel().forceColorSpaceRGB().getRenderedImage();
                    } else {
                        image = iw.bandMerge(3).forceComponentColorModel().forceColorSpaceRGB()
                                .getRenderedImage();
                    }
                } else if(!hasAlpha) {
                    // no transparency in the original data, so no need to expand to RGB
                    if(transparent) {
                        // we need to expand the image with an alpha channel
                        image = addAlphaChannel(image);
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 0 };
                    } else {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm) };
                    }
                } else {
                    // extract the alpha channel
                    final ImageWorker iw = new ImageWorker(image);
                    final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                    alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
                   
                    if (transparent) {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 0 };
                    } else {
                        bgValues = new double[] { mapToGrayColor(bgColor, ccm), 255 };
                    }
                }

                // get back the ColorModel
                cm = image.getColorModel();
                ccm = (ComponentColorModel) cm;
                hasAlpha = cm.hasAlpha();
            }

            if(bgValues == null) {
                if (hasAlpha) {
                    // get alpha
                  final ImageWorker iw = new ImageWorker(image);
                    final RenderedImage alpha = iw.retainLastBand().getRenderedImage();
                    alphaChannels = new PlanarImage[] { PlanarImage.wrapRenderedImage(alpha) };
   
                    if (transparent) {
                        bgValues = new double[] { bgColor.getRed(), bgColor.getGreen(),
                                bgColor.getBlue(), 0 };
View Full Code Here

    }

    private static RenderedImage applyPalette(RenderedImage canvas) {
        if (!(canvas.getColorModel() instanceof IndexColorModel)) {
            // try to force a RGBA setup
            ImageWorker imageWorker = new ImageWorker(canvas);
            RenderedImage image = imageWorker.rescaleToBytes().forceComponentColorModel()
                    .getRenderedImage();
            ColorIndexer indexer = new Quantizer(256).subsample().buildColorIndexer(image);

            // if we have an indexer transform the image
            if (indexer != null) {
View Full Code Here

                // writer = new PNGJWriter();
                // Check if the input object is an OutputStream
                if (destination instanceof OutputStream) {
                    boolean isScanlinePresent = writer.isScanlineSupported(image);
                    if (!isScanlinePresent) {
                        image = new ImageWorker(image).rescaleToBytes().forceComponentColorModel()
                                .getRenderedImage();
                    }
                    Object filterObj = null;
                    if (map != null) {
                        filterObj = map.get(FILTER_TYPE);
View Full Code Here

TOP

Related Classes of org.geotools.image.ImageWorker

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.