Example usage for java.awt RenderingHints RenderingHints

List of usage examples for java.awt RenderingHints RenderingHints

Introduction

In this page you can find the example usage for java.awt RenderingHints RenderingHints.

Prototype

public RenderingHints(Key key, Object value) 

Source Link

Document

Constructs a new object with the specified key/value pair.

Usage

From source file:com.alibaba.simpleimage.ScaleTest.java

public PlanarImage doScaleBicubic(PlanarImage op) throws Exception {
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(op);//w  w w  .  ja  v a  2s  .c  o m
    pb.add(scale);
    pb.add(scale);
    pb.add(0.0F);
    pb.add(0.0F);
    pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    op = JAI.create("scale", pb, qualityHints);

    return op;
}

From source file:com.alibaba.simpleimage.ScaleTest.java

public PlanarImage doScaleBicubic2(PlanarImage op) throws Exception {
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(op);/*from   www  .j  a  va  2s.  co m*/
    pb.add(scale);
    pb.add(scale);
    pb.add(0.0F);
    pb.add(0.0F);
    pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    op = JAI.create("scale", pb, qualityHints);

    return op;
}

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   w w  w  .  ja va  2s  . 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);
        }
    }
}

From source file:com.alibaba.simpleimage.ScaleTest.java

public PlanarImage doSubsampleAverage(PlanarImage op) throws Exception {
    double zoom = dScale;
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(op);/*w ww .j a va 2s  . c o m*/
    pb.add(zoom);
    pb.add(zoom);

    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    RenderedOp zoomOp = JAI.create("SubsampleAverage", pb, qualityHints);

    return zoomOp;
}

From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java

public void writeTo(final OutputStream out) throws ServiceException, IOException {
    Timer timer = new Timer();

    // single layer? -> request ENCODED_IMAGE
    if (mapContext.getLayerCount() == 1) {
        MapLayer mapLayer = mapContext.getLayers()[0];
        ILayer layer = loader.findLayer(mapLayer);
        try {//w w  w  .j  a  va2  s .c  om
            Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE);

            ProcessorRequest request = prepareProcessorRequest();
            pipeline.process(request, new ResponseHandler() {
                public void handle(ProcessorResponse pipeResponse) throws Exception {

                    HttpServletResponse response = GeoServerWms.response.get();
                    if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                        log.info("Response: 304!");
                        response.setStatus(304);
                    } else {
                        long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                        // allow caches and browser clients to cache for 1h
                        //response.setHeader( "Cache-Control", "public,max-age=3600" );
                        if (lastModified > 0) {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Last-Modified", lastModified);
                        } else {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Expires", 0);
                        }

                        byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                        int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                        out.write(chunk, 0, len);
                    }
                }
            });
            log.debug("    flushing response stream. (" + timer.elapsedTime() + "ms)");
            out.flush();
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    // multiple layers -> render into one image
    else {
        List<Job> jobs = new ArrayList();
        final Map<MapLayer, Image> images = new HashMap();

        // run jobs for all layers
        for (final MapLayer mapLayer : mapContext.getLayers()) {
            final ILayer layer = loader.findLayer(mapLayer);
            // job
            UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                        // XXX this excludes Cache304 (which support EncodedImageResponse only)
                        Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE);

                        GetMapRequest targetRequest = prepareProcessorRequest();
                        pipeline.process(targetRequest, new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                                Image layerImage = ((ImageResponse) pipeResponse).getImage();
                                images.put(mapLayer, layerImage);
                            }
                        });
                    } catch (Exception e) {
                        // XXX put a special image in the map
                        log.warn("", e);
                        images.put(mapLayer, null);
                        throw e;
                    }
                }
            };
            job.schedule();
            jobs.add(job);
        }

        // join jobs
        for (Job job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                // XXX put a special image in the map
                log.warn("", e);
            }
        }

        // put images together (MapContext order)
        Graphics2D g = null;
        try {
            // result image
            BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(),
                    null, true);
            g = result.createGraphics();

            // rendering hints
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
            hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
            g.setRenderingHints(hints);

            for (MapLayer mapLayer : mapContext.getLayers()) {
                Image layerImage = images.get(mapLayer);

                // load image data
                //                  new javax.swing.ImageIcon( image ).getImage();

                ILayer layer = loader.findLayer(mapLayer);
                int rule = AlphaComposite.SRC_OVER;
                float alpha = ((float) layer.getOpacity()) / 100;

                g.setComposite(AlphaComposite.getInstance(rule, alpha));
                g.drawImage(layerImage, 0, 0, null);
            }
            encodeImage(result, out);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }
    }
}

From source file:org.polymap.core.data.image.RasterRenderProcessor.java

protected Image getMap(Set<ILayer> layers, int width, int height, ReferencedEnvelope bbox) {
    // mapContext
    synchronized (this) {
        // check style objects
        boolean needsNewContext = false;

        // create mapContext
        if (mapContext == null || needsNewContext) {
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }/*from   w  w w.  j av a2  s.  co  m*/
            // add to mapContext
            mapContext = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    IGeoResource res = layer.getGeoResource();
                    if (res == null) {
                        throw new IllegalStateException("Unable to find geo resource of layer: " + layer);
                    }
                    AbstractRasterService service = (AbstractRasterService) res.service(null);
                    log.debug("    service: " + service);

                    log.debug("    CRS: " + layer.getCRS());
                    AbstractGridCoverage2DReader reader = service.getReader(layer.getCRS(), null);

                    Style style = createRGBStyle(reader);
                    if (style == null) {
                        log.warn("Error creating RGB style, trying greyscale...");
                        style = createGreyscaleStyle(1);
                    }
                    mapContext.addLayer(reader, style);
                    styles.put(layer, style);
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                }
            }
        } else {
        }
    }

    // render
    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    final Graphics2D g = result.createGraphics();
    try {
        StreamingRenderer renderer = new StreamingRenderer();

        // error handler
        renderer.addRenderListener(new RenderListener() {
            public void featureRenderer(SimpleFeature feature) {
            }

            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:oulib.aws.s3.S3Util.java

/**
 * Generate a small tiff file from large Tiff S3 bucket object <br>
 * Note: the small tiff file will have the same key path as the original one
 * //from ww  w . j  ava2  s  .  com
 * @param s3client : S3 client
 * @param s3 : S3 object that con
 * @param targetBucketName : the bucket that stores the small tiff file
 * @param targetKey : key of the object in the target bucket
 * @param compressionRate : compression rate
 * @return : PutObjectResult
 */
public static PutObjectResult generateSmallTiff(AmazonS3 s3client, S3Object s3, String targetBucketName,
        String targetKey, double compressionRate) {

    PutObjectResult result = null;
    ByteArrayOutputStream bos = null;
    ByteArrayOutputStream os = null;
    ByteArrayInputStream is = null;
    S3ObjectInputStream s = null;
    ByteArrayInputStream byteInputStream = null;

    try {
        System.setProperty("com.sun.media.jai.disableMediaLib", "true");

        bos = new ByteArrayOutputStream();
        s = s3.getObjectContent();
        byte[] bytes = IOUtils.toByteArray(s);
        byteInputStream = new ByteArrayInputStream(bytes);

        TIFFDecodeParam param = new TIFFDecodeParam();
        ImageDecoder dec = ImageCodec.createImageDecoder("TIFF", byteInputStream, param);

        RenderedImage image = dec.decodeAsRenderedImage();

        RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        RenderedOp resizedImage = JAI.create("SubsampleAverage", image, compressionRate, compressionRate,
                qualityHints);

        TIFFEncodeParam params = new com.sun.media.jai.codec.TIFFEncodeParam();

        resizedImage = JAI.create("encode", resizedImage, bos, "TIFF", params);

        BufferedImage imagenew = resizedImage.getSourceImage(0).getAsBufferedImage();

        os = new ByteArrayOutputStream();
        ImageIO.write(imagenew, "tif", os);
        is = new ByteArrayInputStream(os.toByteArray());

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(os.toByteArray().length);
        metadata.setContentType("image/tiff");
        metadata.setLastModified(new Date());

        os.close();

        imagenew.flush();

        result = s3client.putObject(new PutObjectRequest(targetBucketName, targetKey, is, metadata));
    } catch (IOException | AmazonClientException ex) {
        Logger.getLogger(S3Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
            if (s != null) {
                s.close();
            }
            if (byteInputStream != null) {
                byteInputStream.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(S3Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return result;
}

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

@Override
public void draw(Graphics2D graphics, MapContent map, MapViewport viewport) {
    try {/*from  www.  j a v  a 2 s.  c  om*/
        if (tiles.size() > 0) {
            Collection<Callable<ImageResult>> callables = new ArrayList<Callable<ImageResult>>(tiles.size());
            // Build the image downloading threads
            for (RasterTile tile : tiles) {
                RasterImageDownloadCallable downloadThread = new RasterImageDownloadCallable(
                        DOWNLOAD_MAX_ATTEMPTS, tile);
                callables.add(downloadThread);
            }
            // Loop until all images are downloaded or timeout is reached
            long totalTimeout = DOWNLOAD_TIMEOUT + DOWNLOAD_TIMEOUT_ONE_TILE * tiles.size();
            log.debug("=== total timeout (millis): {}", totalTimeout);
            ExecutorService service = Executors.newFixedThreadPool(DOWNLOAD_MAX_THREADS);
            List<Future<ImageResult>> futures = service.invokeAll(callables, totalTimeout,
                    TimeUnit.MILLISECONDS);
            // determine the pixel bounds of the mosaic
            Bbox pixelBounds = getPixelBounds(tiles);
            // create the images for the mosaic
            List<RenderedImage> images = new ArrayList<RenderedImage>();
            for (Future<ImageResult> future : futures) {
                ImageResult result = null;
                if (future.isDone()) {
                    try {
                        result = future.get();
                        // create a rendered image
                        if (result.getImage() != null && result.getImage().length > 0) {
                            RenderedImage image = JAI.create("stream",
                                    new ByteArraySeekableStream(result.getImage()));
                            // convert to common direct color model (some images have their own indexed color model)
                            RenderedImage colored = toDirectColorModel(image);

                            // translate to the correct position in the tile grid
                            double xOffset = result.getRasterImage().getCode().getX() * tileWidth
                                    - pixelBounds.getX();
                            double yOffset;
                            // TODO: in some cases, the y-index is up (e.g. WMS), should be down for
                            // all layers !!!!
                            if (isYIndexUp(tiles)) {
                                yOffset = result.getRasterImage().getCode().getY() * tileHeight
                                        - pixelBounds.getY();
                            } else {
                                yOffset = (pixelBounds.getMaxY()
                                        - (result.getRasterImage().getCode().getY() + 1) * tileHeight);
                            }
                            log.debug("adding to(" + xOffset + "," + yOffset + "), url = "
                                    + result.getRasterImage().getUrl());
                            RenderedImage translated = TranslateDescriptor.create(colored, (float) xOffset,
                                    (float) yOffset, new InterpolationNearest(), null);
                            images.add(translated);
                        }
                    } catch (ExecutionException e) {
                        addLoadError(graphics, (ImageException) (e.getCause()), viewport);
                        log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage());
                    } catch (Exception e) {
                        log.warn("Missing tile " + result.getRasterImage().getUrl());
                        log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage());
                    }
                }
            }

            if (images.size() > 0) {
                ImageLayout imageLayout = new ImageLayout(0, 0, (int) pixelBounds.getWidth(),
                        (int) pixelBounds.getHeight());
                imageLayout.setTileWidth(tileWidth);
                imageLayout.setTileHeight(tileHeight);

                // create the mosaic image
                ParameterBlock pbMosaic = new ParameterBlock();
                pbMosaic.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY);
                for (RenderedImage renderedImage : images) {
                    pbMosaic.addSource(renderedImage);
                }
                RenderedOp mosaic = JAI.create("mosaic", pbMosaic,
                        new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout));
                try {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    log.debug("rendering to buffer...");
                    ImageIO.write(mosaic, "png", baos);
                    log.debug("rendering done, size = " + baos.toByteArray().length);
                    RasterTile mosaicTile = new RasterTile();
                    mosaicTile.setBounds(getWorldBounds(tiles));
                    log.info("application bounds = " + mosaicTile.getBounds());
                    ImageResult mosaicResult = new ImageResult(mosaicTile);
                    mosaicResult.setImage(baos.toByteArray());
                    addImage(graphics, mosaicResult, viewport);
                } catch (IOException e) {
                    log.warn("could not write mosaic image " + e.getMessage());
                }
            }
        }
    } catch (InterruptedException e) {
        log.warn("rendering {} to {} failed : ", getTitle(), viewport.getBounds());
    }
}

From source file:ch.entwine.weblounge.preview.jai.JAIPreviewGenerator.java

/**
 * Resizes the given image to what is defined by the image style and writes
 * the result to the output stream.// w ww .j a v  a  2s  . co  m
 * 
 * @param is
 *          the input stream
 * @param os
 *          the output stream
 * @param format
 *          the image format
 * @param style
 *          the style
 * @throws IllegalArgumentException
 *           if the image is in an unsupported format
 * @throws IllegalArgumentException
 *           if the input stream is empty
 * @throws IOException
 *           if reading from or writing to the stream fails
 * @throws OutOfMemoryError
 *           if the image is too large to be processed in memory
 */
private void style(InputStream is, OutputStream os, String format, ImageStyle style)
        throws IllegalArgumentException, IOException, OutOfMemoryError {

    // Does the input stream contain any data?
    if (is.available() == 0)
        throw new IllegalArgumentException("Empty input stream was passed to image styling");

    // Do we need to do any work at all?
    if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) {
        logger.trace("No scaling needed, performing a noop stream copy");
        IOUtils.copy(is, os);
        return;
    }

    SeekableStream seekableInputStream = null;
    RenderedOp image = null;
    try {
        // Load the image from the given input stream
        seekableInputStream = new FileCacheSeekableStream(is);
        image = JAI.create("stream", seekableInputStream);
        if (image == null)
            throw new IOException("Error reading image from input stream");

        // Get the original image size
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // Resizing
        float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);

        RenderingHints scaleHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        scaleHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        scaleHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        scaleHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        int scaledWidth = Math.round(scale * image.getWidth());
        int scaledHeight = Math.round(scale * image.getHeight());
        int cropX = 0;
        int cropY = 0;

        // If either one of scaledWidth or scaledHeight is < 1.0, then
        // the scale needs to be adapted to scale to 1.0 exactly and accomplish
        // the rest by cropping.

        if (scaledWidth < 1.0f) {
            scale = 1.0f / imageWidth;
            scaledWidth = 1;
            cropY = imageHeight - scaledHeight;
            scaledHeight = Math.round(imageHeight * scale);
        } else if (scaledHeight < 1.0f) {
            scale = 1.0f / imageHeight;
            scaledHeight = 1;
            cropX = imageWidth - scaledWidth;
            scaledWidth = Math.round(imageWidth * scale);
        }

        if (scale > 1.0) {
            ParameterBlock scaleParams = new ParameterBlock();
            scaleParams.addSource(image);
            scaleParams.add(scale).add(scale).add(0.0f).add(0.0f);
            scaleParams.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
            image = JAI.create("scale", scaleParams, scaleHints);
        } else if (scale < 1.0) {
            ParameterBlock subsampleAverageParams = new ParameterBlock();
            subsampleAverageParams.addSource(image);
            subsampleAverageParams.add(Double.valueOf(scale));
            subsampleAverageParams.add(Double.valueOf(scale));
            image = JAI.create("subsampleaverage", subsampleAverageParams, scaleHints);
        }

        // Cropping
        cropX = (int) Math.max(cropX,
                (float) Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
        cropY = (int) Math.max(cropY,
                (float) Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));

        if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {

            ParameterBlock cropTopLeftParams = new ParameterBlock();
            cropTopLeftParams.addSource(image);
            cropTopLeftParams.add(cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
            cropTopLeftParams.add(cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
            cropTopLeftParams.add(scaledWidth - Math.max(cropX, 0.0f)); // width
            cropTopLeftParams.add(scaledHeight - Math.max(cropY, 0.0f)); // height

            RenderingHints croppingHints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                    BorderExtender.createInstance(BorderExtender.BORDER_COPY));

            image = JAI.create("crop", cropTopLeftParams, croppingHints);
        }

        // Write resized/cropped image encoded as JPEG to the output stream
        ParameterBlock encodeParams = new ParameterBlock();
        encodeParams.addSource(image);
        encodeParams.add(os);
        encodeParams.add("jpeg");
        JAI.create("encode", encodeParams);

    } catch (Throwable t) {
        if (t.getClass().getName().contains("ImageFormat")) {
            throw new IllegalArgumentException(t.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(seekableInputStream);
        if (image != null)
            image.dispose();
    }
}

From source file:org.polymap.core.data.feature.FeatureRenderProcessor2.java

protected Image getMap(final Set<ILayer> layers, int width, int height, final ReferencedEnvelope bbox) {
    //        Logger wfsLog = Logging.getLogger( "org.geotools.data.wfs.protocol.http" );
    //        wfsLog.setLevel( Level.FINEST );

    // mapContext
    MapContext mapContext = mapContextRef.get(new Supplier<MapContext>() {
        public MapContext get() {
            log.debug("Creating new MapContext... ");
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }/*from w  w w .j  a v a 2  s . c  om*/
            // add to mapContext
            MapContext result = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    FeatureSource fs = PipelineFeatureSource.forLayer(layer, false);
                    log.debug("        FeatureSource: " + fs);
                    log.debug("            fs.getName(): " + fs.getName());

                    Style style = layer.getStyle().resolve(Style.class, null);
                    if (style == null) {
                        log.warn("            fs.getName(): " + fs.getName());
                        style = new DefaultStyles().findStyle(fs);
                    }
                    result.addLayer(fs, style);

                    // watch layer for style changes
                    LayerStyleListener listener = new LayerStyleListener(mapContextRef);
                    if (watchedLayers.putIfAbsent(layer, listener) == null) {
                        layer.addPropertyChangeListener(listener);
                    }
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                } catch (PipelineIncubationException e) {
                    log.warn("No pipeline.", e);
                }
            }
            log.debug("created: " + result);
            return result;
        }
    });
    log.debug("using: " + mapContext);

    // render
    //        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //        GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    //        VolatileImage result = gc.createCompatibleVolatileImage( width, height, Transparency.TRANSLUCENT );

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    result.setAccelerationPriority(1);

    final Graphics2D g = result.createGraphics();
    //        log.info( "IMAGE: accelerated=" + result.getCapabilities( g.getDeviceConfiguration() ).isAccelerated() );

    try {
        final StreamingRenderer renderer = new StreamingRenderer();

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_SPEED);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // error handler
        renderer.addRenderListener(new RenderListener() {
            int featureCount = 0;

            @Override
            public void featureRenderer(SimpleFeature feature) {
                //                  if (++featureCount == 100) {
                //                      log.info( "Switch off antialiasing!" );
                //                      RenderingHints off = new RenderingHints(
                //                              RenderingHints.KEY_ANTIALIASING,
                //                              RenderingHints.VALUE_ANTIALIAS_OFF );
                //                      renderer.setJava2DHints( off );
                //                      g.setRenderingHints( off );
                //                  }
            }

            @Override
            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}