Example usage for java.awt.image BufferedImage TYPE_INT_ARGB

List of usage examples for java.awt.image BufferedImage TYPE_INT_ARGB

Introduction

In this page you can find the example usage for java.awt.image BufferedImage TYPE_INT_ARGB.

Prototype

int TYPE_INT_ARGB

To view the source code for java.awt.image BufferedImage TYPE_INT_ARGB.

Click Source Link

Document

Represents an image with 8-bit RGBA color components packed into integer pixels.

Usage

From source file:org.geoserver.wms.legendgraphic.ColorMapLegendCreator.java

private Queue<BufferedImage> createBody() {

    final Queue<BufferedImage> queue = new LinkedList<BufferedImage>();

    ////from  w ww .  j  a v  a 2s  . c  om
    // draw the various elements
    //
    // create the boxes for drawing later
    final int rowHeight = (int) Math.round(rowH);
    final int colorWidth = (int) Math.round(colorW);
    final int ruleWidth = (int) Math.round(ruleW);
    final int labelWidth = (int) Math.round(labelW);
    final Rectangle clipboxA = new Rectangle(0, 0, colorWidth, rowHeight);
    final Rectangle clipboxB = new Rectangle(0, 0, ruleWidth, rowHeight);
    final Rectangle clipboxC = new Rectangle(0, 0, labelWidth, rowHeight);

    //
    // Body
    //
    //
    // draw the various bodyCells
    for (ColorMapEntryLegendBuilder row : bodyRows) {

        //
        // row number i
        //
        // get element for color default behavior
        final Cell colorCell = row.getColorManager();
        // draw it
        final BufferedImage colorCellLegend = new BufferedImage(colorWidth, rowHeight,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D rlg = colorCellLegend.createGraphics();
        rlg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        rlg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        colorCell.draw(rlg, clipboxA, border);
        rlg.dispose();

        BufferedImage ruleCellLegend = null;
        if (forceRule) {
            // get element for rule
            final Cell ruleCell = row.getRuleManager();
            // draw it
            ruleCellLegend = new BufferedImage(ruleWidth, rowHeight, BufferedImage.TYPE_INT_ARGB);
            rlg = ruleCellLegend.createGraphics();
            rlg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            rlg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            ruleCell.draw(rlg, clipboxB, borderRule);
            rlg.dispose();
        }

        // draw it if it is present
        if (labelWidth > 0) {
            // get element for label
            final Cell labelCell = row.getLabelManager();
            if (labelCell != null) {
                final BufferedImage labelCellLegend = new BufferedImage(labelWidth, rowHeight,
                        BufferedImage.TYPE_INT_ARGB);
                rlg = labelCellLegend.createGraphics();
                rlg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                rlg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                labelCell.draw(rlg, clipboxC, borderLabel);
                rlg.dispose();

                //
                // merge the bodyCells for this row
                //
                //

                final Map<Key, Object> hintsMap = new HashMap<Key, Object>();
                queue.add(LegendUtils.hMergeBufferedImages(colorCellLegend, ruleCellLegend, labelCellLegend,
                        hintsMap, transparent, backgroundColor, dx));
            } else {
                final Map<Key, Object> hintsMap = new HashMap<Key, Object>();
                queue.add(LegendUtils.hMergeBufferedImages(colorCellLegend, ruleCellLegend, null, hintsMap,
                        transparent, backgroundColor, dx));
            }

        } else {
            //
            // merge the bodyCells for this row
            //
            //

            final Map<Key, Object> hintsMap = new HashMap<Key, Object>();
            queue.add(LegendUtils.hMergeBufferedImages(colorCellLegend, ruleCellLegend, null, hintsMap,
                    transparent, backgroundColor, dx));

        }

    }

    // return the list of legends
    return queue;// mergeRows(queue);
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

protected void calcColoredMaps(Color[] colors) {
    // Berechnet die eingefrbten Texturen, z.B. fr Gebude
    ArrayList<CoRImage> tList = new ArrayList<CoRImage>();
    tList.addAll(coloredImgMap.values());
    coloredImgMap.clear();/*from w  w w .  j av a2  s .  c  o m*/
    for (int i = 0; i < tList.size(); i++) {
        BufferedImage im = (BufferedImage) tList.get(i).getImage();
        for (int playerId = 0; playerId < colors.length; playerId++) {
            BufferedImage preImg = new BufferedImage(im.getWidth(), im.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            for (int x = 0; x < im.getWidth(); x++) {
                for (int y = 0; y < im.getHeight(); y++) {
                    // Das ganze Raster durchgehen und Farben ersetzen
                    // Ersetzfarbe da?
                    int rgb = im.getRGB(x, y);

                    float[] col = Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, null);
                    if (col[0] >= 0.8583333f && col[0] <= 0.8666666f) {
                        // Ja, ersetzen
                        Color tc = colors[playerId];
                        int targetC = Color.HSBtoRGB(
                                Color.RGBtoHSB(tc.getRed(), tc.getGreen(), tc.getBlue(), null)[0], 1.0f,
                                col[2]);
                        int a = (rgb >> 24) & 0xff;
                        targetC = (targetC & (~(0xff << 24)) | (a << 24));
                        preImg.setRGB(x, y, targetC);

                    } else {
                        preImg.setRGB(x, y, im.getRGB(x, y));
                    }
                }
            }
            // Bild berechnet, einfgen
            CoRImage newImg = new CoRImage(preImg);
            newImg.setImageName(tList.get(i).getImageName());
            coloredImgMap.put(newImg.getImageName() + playerId, newImg);
        }

    }
}

From source file:cish.CISH.java

/**
 * Inits some icons.//from  w  w  w  .  j  a  va  2 s  .c  om
 */
private void initComponents2() {
    BufferedImage bi = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = bi.createGraphics();
    g.setColor(new Color(COLORS[0][0], COLORS[0][1], COLORS[0][2]));
    g.drawRect(0, 0, 7, 7);
    jLabel3.setIcon(new ImageIcon(bi));

    bi = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
    g = bi.createGraphics();
    g.setColor(new Color(COLORS[1][0], COLORS[1][1], COLORS[1][2]));
    g.drawRect(0, 0, 7, 7);
    jLabel4.setIcon(new ImageIcon(bi));

    bi = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
    g = bi.createGraphics();
    g.setColor(new Color(COLORS[4][0], COLORS[4][1], COLORS[4][2]));
    g.drawRect(0, 0, 7, 7);
    jLabel5.setIcon(new ImageIcon(bi));
}

From source file:com.moviejukebox.plugin.DefaultImagePlugin.java

/**
 * Draw rounded corners on the image//from w w  w  .ja v  a  2  s  .  c  om
 *
 * @param bi
 * @return
 */
protected BufferedImage drawRoundCorners(BufferedImage bi) {
    BufferedImage newImg = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D newGraphics = newImg.createGraphics();
    newGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    RoundRectangle2D.Double rect = new RoundRectangle2D.Double(0, 0, bi.getWidth(), bi.getHeight(),
            rcqFactor * cornerRadius, rcqFactor * cornerRadius);
    newGraphics.setClip(rect);
    newGraphics.drawImage(bi, 0, 0, null);

    newGraphics.dispose();
    return newImg;
}

From source file:org.deegree.portal.standard.wms.control.DynLegendListener.java

/**
 * In case the legend can not be obtained from the OGCLayer, this method is called to create a dummy legend image
 * plus the legend title/*from w w w. j  a v a2 s. co  m*/
 * 
 * @param layerName
 * @return BufferedImage holding the created dummy legend
 */
private BufferedImage createMissingLegend(String layerName) {
    LOG.logDebug("URL is null. Drawing the image from a missingImage variable in init params");
    BufferedImage missingLegend = new BufferedImage(80, 15, BufferedImage.TYPE_INT_RGB);
    Graphics g = missingLegend.getGraphics();
    Rectangle2D rect = g.getFontMetrics().getStringBounds(layerName, g);
    g.dispose();
    missingLegend = new BufferedImage(rect.getBounds().width + 80, missingImg.getHeight() + 15,
            BufferedImage.TYPE_INT_ARGB);
    g = missingLegend.getGraphics();
    g.drawImage(missingImg, 0, 0, null);
    g.setColor(Color.RED);
    if (useLayerTitle) {
        g.drawString(layerName, missingImg.getWidth() + 5,
                missingImg.getHeight() / 2 + g.getFont().getSize() / 2);
    }
    g.dispose();

    return missingLegend;
}

From source file:edu.umn.cs.spatialHadoop.operations.PyramidPlot.java

private static void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException {
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);

    Color strokeColor = params.getColor("color", Color.BLACK);

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;//  ww  w.  j a  v  a 2 s  .c o m
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMBR = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    boolean keepAspectRatio = params.is("keep-ratio", true);
    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() > fileMBR.getHeight()) {
            fileMBR.y1 -= (fileMBR.getWidth() - fileMBR.getHeight()) / 2;
            fileMBR.y2 = fileMBR.y1 + fileMBR.getWidth();
        } else {
            fileMBR.x1 -= (fileMBR.getHeight() - fileMBR.getWidth() / 2);
            fileMBR.x2 = fileMBR.x1 + fileMBR.getHeight();
        }
    }

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    boolean adaptiveSampling = params.getBoolean("sample", false);

    int numLevels = params.getInt("numlevels", 7);

    float[] levelProb = new float[numLevels];
    double[] scale2 = new double[numLevels];
    double[] scale = new double[numLevels];
    levelProb[0] = params.getFloat(GeometricPlot.AdaptiveSampleRatio, 0.1f);
    // Size of the whole file in pixels at the f

    scale2[0] = (double) tileWidth * tileHeight / (fileMBR.getWidth() * fileMBR.getHeight());
    scale[0] = Math.sqrt(scale2[0]);
    for (int level = 1; level < numLevels; level++) {
        levelProb[level] = levelProb[level - 1] * 4;
        scale2[level] = scale2[level - 1] * (1 << level) * (1 << level);
        scale[level] = scale[level - 1] * (1 << level);
    }

    Map<TileIndex, BufferedImage> tileImages = new HashMap<PyramidPlot.TileIndex, BufferedImage>();

    Map<TileIndex, Graphics2D> tileGraphics = new HashMap<PyramidPlot.TileIndex, Graphics2D>();

    GridInfo bottomGrid = new GridInfo(fileMBR.x1, fileMBR.y1, fileMBR.x2, fileMBR.y2);
    bottomGrid.rows = bottomGrid.columns = (int) Math.round(Math.pow(2, numLevels - 1));

    TileIndex tileIndex = new TileIndex();
    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeMBR = shape.getMBR();
            if (shapeMBR != null) {
                int min_level = 0;

                if (adaptiveSampling) {
                    // Special handling for NASA data
                    double p = Math.random();
                    // Skip levels that do not satisfy the probability
                    while (min_level < numLevels && p > levelProb[min_level])
                        min_level++;
                }

                java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                for (tileIndex.level = numLevels - 1; tileIndex.level >= min_level; tileIndex.level--) {
                    if (gradualFade && !(shape instanceof Point)) {
                        double areaInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight())
                                * scale[tileIndex.level];
                        if (areaInPixels < 1.0 && Math.round(areaInPixels * 255) < 1.0) {
                            // This shape can be safely skipped as it is too small to be plotted
                            return;
                        }
                    }

                    for (int i = 0; i < overlappingCells.width; i++) {
                        tileIndex.x = i + overlappingCells.x;
                        for (int j = 0; j < overlappingCells.height; j++) {
                            tileIndex.y = j + overlappingCells.y;
                            // Draw in image associated with this tile
                            Graphics2D g;
                            {
                                g = tileGraphics.get(tileIndex);
                                if (g == null) {
                                    TileIndex key = tileIndex.clone();
                                    BufferedImage image = new BufferedImage(tileWidth, tileHeight,
                                            BufferedImage.TYPE_INT_ARGB);
                                    if (tileImages.put(key, image) != null)
                                        throw new RuntimeException(
                                                "Error! Image is already there but graphics is not "
                                                        + tileIndex);

                                    Color bg_color = new Color(0, 0, 0, 0);

                                    try {
                                        g = image.createGraphics();
                                    } catch (Throwable e) {
                                        g = new SimpleGraphics(image);
                                    }
                                    g.setBackground(bg_color);
                                    g.clearRect(0, 0, tileWidth, tileHeight);
                                    g.setColor(strokeColor);
                                    // Coordinates of this tile in image coordinates
                                    g.translate(-(tileWidth * tileIndex.x), -(tileHeight * tileIndex.y));

                                    tileGraphics.put(key, g);
                                }
                            }

                            shape.draw(g, fileMBR, tileWidth * (1 << tileIndex.level),
                                    tileHeight * (1 << tileIndex.level), scale2[tileIndex.level]);
                        }
                    }
                    // Shrink overlapping cells to match the upper level
                    int updatedX1 = overlappingCells.x / 2;
                    int updatedY1 = overlappingCells.y / 2;
                    int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                    int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                    overlappingCells.x = updatedX1;
                    overlappingCells.y = updatedY1;
                    overlappingCells.width = updatedX2 - updatedX1 + 1;
                    overlappingCells.height = updatedY2 - updatedY1 + 1;
                }
            }
        }
        reader.close();
    }
    // Write image to output
    for (Map.Entry<TileIndex, Graphics2D> tileGraph : tileGraphics.entrySet()) {
        tileGraph.getValue().dispose();
    }
    FileSystem outFS = outFile.getFileSystem(params);
    for (Map.Entry<TileIndex, BufferedImage> tileImage : tileImages.entrySet()) {
        tileIndex = tileImage.getKey();
        BufferedImage image = tileImage.getValue();
        if (vflip) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -image.getHeight());
            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            image = op.filter(image, null);
            tileIndex.y = ((1 << tileIndex.level) - 1) - tileIndex.y;
        }
        Path imagePath = new Path(outFile, tileIndex.getImageFileName());
        FSDataOutputStream outStream = outFS.create(imagePath);
        ImageIO.write(image, "png", outStream);
        outStream.close();
    }
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java

private Object prepareMap(List<OrderedDatasource<?>> datasources, String type, int originalWidth,
        int originalHeight, int width, int height, Envelope bbox, int resolution) throws ProcessletException {
    if ("net.sf.jasperreports.engine.JRRenderable".equals(type)) {
        return new MapRenderable(datasources, bbox, resolution);
    } else {/*from  w ww.j  av  a 2  s.c o m*/
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.getGraphics();
        for (OrderedDatasource<?> datasource : datasources) {
            BufferedImage image = datasource.getImage(width, height, bbox);
            if (image != null) {
                g.drawImage(image, 0, 0, null);
            }
        }
        g.dispose();
        return convertImageToReportFormat(type, bi);
    }
}

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

private byte[] createImage(int width, int height, String text) throws IOException {
    if (width < 0) {
        width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH;
    }/*from  w ww. j ava  2 s. c  o  m*/
    if (height < 0) {
        height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = (Graphics2D) img.getGraphics();
    g2.setBackground(new Color(220, 220, 220));

    Dimension size;
    float fontSize = g2.getFont().getSize();
    // Make the text as large as possible.
    do {
        g2.setFont(g2.getFont().deriveFont(fontSize));
        FontMetrics metrics = g2.getFontMetrics(g2.getFont());
        int hgt = metrics.getHeight();
        int adv = metrics.stringWidth(text);
        size = new Dimension(adv + 2, hgt + 2);
        fontSize = fontSize + 1f;
    } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height));

    g2.setColor(Color.DARK_GRAY);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2);
    g2.setColor(Color.LIGHT_GRAY);
    g2.drawRect(0, 0, width - 1, height - 1);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height);
    ImageIO.write(img, "png", baos);
    baos.flush();
    byte[] rawBytes = baos.toByteArray();
    baos.close();

    return rawBytes;
}

From source file:edu.umn.cs.spatialHadoop.visualization.MultilevelPlot.java

private static void plotLocal(Path[] inFiles, final Path outPath, final Class<? extends Plotter> plotterClass,
        final OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException {
    final boolean vflip = params.getBoolean("vflip", true);

    OperationsParams mbrParams = new OperationsParams(params);
    mbrParams.setBoolean("background", false);
    final Rectangle inputMBR = params.get("mbr") != null ? params.getShape("mbr").getMBR()
            : FileMBR.fileMBR(inFiles, mbrParams);
    OperationsParams.setShape(params, InputMBR, inputMBR);

    // Retrieve desired output image size and keep aspect ratio if needed
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);
    // Adjust width and height if aspect ratio is to be kept
    if (params.getBoolean("keepratio", true)) {
        // Expand input file to a rectangle for compatibility with the pyramid
        // structure
        if (inputMBR.getWidth() > inputMBR.getHeight()) {
            inputMBR.y1 -= (inputMBR.getWidth() - inputMBR.getHeight()) / 2;
            inputMBR.y2 = inputMBR.y1 + inputMBR.getWidth();
        } else {//from w w w.j  a v  a  2 s .c  o m
            inputMBR.x1 -= (inputMBR.getHeight() - inputMBR.getWidth()) / 2;
            inputMBR.x2 = inputMBR.x1 + inputMBR.getHeight();
        }
    }

    String outFName = outPath.getName();
    int extensionStart = outFName.lastIndexOf('.');
    final String extension = extensionStart == -1 ? ".png" : outFName.substring(extensionStart);

    // Start reading input file
    Vector<InputSplit> splits = new Vector<InputSplit>();
    final SpatialInputFormat3<Rectangle, Shape> inputFormat = new SpatialInputFormat3<Rectangle, Shape>();
    for (Path inFile : inFiles) {
        FileSystem inFs = inFile.getFileSystem(params);
        if (!OperationsParams.isWildcard(inFile) && inFs.exists(inFile) && !inFs.isDirectory(inFile)) {
            if (SpatialSite.NonHiddenFileFilter.accept(inFile)) {
                // Use the normal input format splitter to add this non-hidden file
                Job job = Job.getInstance(params);
                SpatialInputFormat3.addInputPath(job, inFile);
                splits.addAll(inputFormat.getSplits(job));
            } else {
                // A hidden file, add it immediately as one split
                // This is useful if the input is a hidden file which is automatically
                // skipped by FileInputFormat. We need to plot a hidden file for the case
                // of plotting partition boundaries of a spatial index
                splits.add(new FileSplit(inFile, 0, inFs.getFileStatus(inFile).getLen(), new String[0]));
            }
        } else {
            Job job = Job.getInstance(params);
            SpatialInputFormat3.addInputPath(job, inFile);
            splits.addAll(inputFormat.getSplits(job));
        }
    }

    try {
        Plotter plotter = plotterClass.newInstance();
        plotter.configure(params);

        String[] strLevels = params.get("levels", "7").split("\\.\\.");
        int minLevel, maxLevel;
        if (strLevels.length == 1) {
            minLevel = 0;
            maxLevel = Integer.parseInt(strLevels[0]);
        } else {
            minLevel = Integer.parseInt(strLevels[0]);
            maxLevel = Integer.parseInt(strLevels[1]);
        }

        GridInfo bottomGrid = new GridInfo(inputMBR.x1, inputMBR.y1, inputMBR.x2, inputMBR.y2);
        bottomGrid.rows = bottomGrid.columns = 1 << maxLevel;

        TileIndex key = new TileIndex();

        // All canvases in the pyramid, one per tile
        Map<TileIndex, Canvas> canvases = new HashMap<TileIndex, Canvas>();
        for (InputSplit split : splits) {
            FileSplit fsplit = (FileSplit) split;
            RecordReader<Rectangle, Iterable<Shape>> reader = inputFormat.createRecordReader(fsplit, null);
            if (reader instanceof SpatialRecordReader3) {
                ((SpatialRecordReader3) reader).initialize(fsplit, params);
            } else if (reader instanceof RTreeRecordReader3) {
                ((RTreeRecordReader3) reader).initialize(fsplit, params);
            } else if (reader instanceof HDFRecordReader) {
                ((HDFRecordReader) reader).initialize(fsplit, params);
            } else {
                throw new RuntimeException("Unknown record reader");
            }

            while (reader.nextKeyValue()) {
                Rectangle partition = reader.getCurrentKey();
                if (!partition.isValid())
                    partition.set(inputMBR);

                Iterable<Shape> shapes = reader.getCurrentValue();

                for (Shape shape : shapes) {
                    Rectangle shapeMBR = shape.getMBR();
                    if (shapeMBR == null)
                        continue;
                    java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                    // Iterate over levels from bottom up
                    for (key.level = maxLevel; key.level >= minLevel; key.level--) {
                        for (key.x = overlappingCells.x; key.x < overlappingCells.x
                                + overlappingCells.width; key.x++) {
                            for (key.y = overlappingCells.y; key.y < overlappingCells.y
                                    + overlappingCells.height; key.y++) {
                                Canvas canvas = canvases.get(key);
                                if (canvas == null) {
                                    Rectangle tileMBR = new Rectangle();
                                    int gridSize = 1 << key.level;
                                    tileMBR.x1 = (inputMBR.x1 * (gridSize - key.x) + inputMBR.x2 * key.x)
                                            / gridSize;
                                    tileMBR.x2 = (inputMBR.x1 * (gridSize - (key.x + 1))
                                            + inputMBR.x2 * (key.x + 1)) / gridSize;
                                    tileMBR.y1 = (inputMBR.y1 * (gridSize - key.y) + inputMBR.y2 * key.y)
                                            / gridSize;
                                    tileMBR.y2 = (inputMBR.y1 * (gridSize - (key.y + 1))
                                            + inputMBR.y2 * (key.y + 1)) / gridSize;
                                    canvas = plotter.createCanvas(tileWidth, tileHeight, tileMBR);
                                    canvases.put(key.clone(), canvas);
                                }
                                plotter.plot(canvas, shape);
                            }
                        }
                        // Update overlappingCells for the higher level
                        int updatedX1 = overlappingCells.x / 2;
                        int updatedY1 = overlappingCells.y / 2;
                        int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                        int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                        overlappingCells.x = updatedX1;
                        overlappingCells.y = updatedY1;
                        overlappingCells.width = updatedX2 - updatedX1 + 1;
                        overlappingCells.height = updatedY2 - updatedY1 + 1;
                    }
                }
            }
            reader.close();
        }

        // Done with all splits. Write output to disk
        LOG.info("Done with plotting. Now writing the output");
        final FileSystem outFS = outPath.getFileSystem(params);

        LOG.info("Writing default empty image");
        // Write a default empty image to be displayed for non-generated tiles
        BufferedImage emptyImg = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = new SimpleGraphics(emptyImg);
        g.setBackground(new Color(0, 0, 0, 0));
        g.clearRect(0, 0, tileWidth, tileHeight);
        g.dispose();

        // Write HTML file to browse the mutlielvel image
        OutputStream out = outFS.create(new Path(outPath, "default.png"));
        ImageIO.write(emptyImg, "png", out);
        out.close();

        // Add an HTML file that visualizes the result using Google Maps
        LOG.info("Writing the HTML viewer file");
        LineReader templateFileReader = new LineReader(
                MultilevelPlot.class.getResourceAsStream("/zoom_view.html"));
        PrintStream htmlOut = new PrintStream(outFS.create(new Path(outPath, "index.html")));
        Text line = new Text();
        while (templateFileReader.readLine(line) > 0) {
            String lineStr = line.toString();
            lineStr = lineStr.replace("#{TILE_WIDTH}", Integer.toString(tileWidth));
            lineStr = lineStr.replace("#{TILE_HEIGHT}", Integer.toString(tileHeight));
            lineStr = lineStr.replace("#{MAX_ZOOM}", Integer.toString(maxLevel));
            lineStr = lineStr.replace("#{MIN_ZOOM}", Integer.toString(minLevel));
            lineStr = lineStr.replace("#{TILE_URL}",
                    "'tile-' + zoom + '-' + coord.x + '-' + coord.y + '" + extension + "'");

            htmlOut.println(lineStr);
        }
        templateFileReader.close();
        htmlOut.close();

        // Write the tiles
        final Entry<TileIndex, Canvas>[] entries = canvases.entrySet().toArray(new Map.Entry[canvases.size()]);
        // Clear the hash map to save memory as it is no longer needed
        canvases.clear();
        int parallelism = params.getInt("parallel", Runtime.getRuntime().availableProcessors());
        Parallel.forEach(entries.length, new RunnableRange<Object>() {
            @Override
            public Object run(int i1, int i2) {
                boolean output = params.getBoolean("output", true);
                try {
                    Plotter plotter = plotterClass.newInstance();
                    plotter.configure(params);
                    for (int i = i1; i < i2; i++) {
                        Map.Entry<TileIndex, Canvas> entry = entries[i];
                        TileIndex key = entry.getKey();
                        if (vflip)
                            key.y = ((1 << key.level) - 1) - key.y;

                        Path imagePath = new Path(outPath, key.getImageFileName() + extension);
                        // Write this tile to an image
                        DataOutputStream outFile = output ? outFS.create(imagePath)
                                : new DataOutputStream(new NullOutputStream());
                        plotter.writeImage(entry.getValue(), outFile, vflip);
                        outFile.close();

                        // Remove entry to allows GC to collect it
                        entries[i] = null;
                    }
                    return null;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }, parallelism);
    } catch (InstantiationException e) {
        throw new RuntimeException("Error creating rastierizer", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Error creating rastierizer", e);
    }
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Builds a combined image layer of all the layers in a saved map.
 * //from  ww w .  j a  v  a  2s . co m
 * @mapWidth
 * @mapHeight
 * @orderedLayers
 * @mapBounds - expects json object {"bottom":"VALUE", "top":"VALUE", "left":"VALUE", "right":"VALUE"}
 */
public BufferedImage getLayersExportCanvas(int mapWidth, int mapHeight, DashboardLayer[] orderedLayers,
        String mapBounds) {
    String bottom;
    String top;
    String right;
    String left;
    String processingFormat = "png"; // needed to allow transparency on each overlay before combining to a single
                                     // map/format
    Graphics mapBaseGraphic = null;
    BufferedImage base = null;

    try {
        base = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
        mapBaseGraphic = base.getGraphics();
        mapBaseGraphic.drawImage(base, 0, 0, null);

        // Get bounds of the map
        try {
            JSONObject mapBoundsObj = new JSONObject(mapBounds);
            bottom = mapBoundsObj.getString("bottom");
            top = mapBoundsObj.getString("top");
            right = mapBoundsObj.getString("right");
            left = mapBoundsObj.getString("left");
        } catch (JSONException e) {
            String error = "Could not parse map bounds.";
            throw new ProgrammingErrorException(error, e);
        }

        // Generates map overlays and combines them into a single map image
        for (DashboardLayer layer : orderedLayers) {
            // if (layer instanceof DashboardThematicLayer)
            // {
            Graphics2D newOverlayBaseGraphic = null;
            Graphics2D mapLayerGraphic2d = null;

            String layersString = GeoserverProperties.getWorkspace() + ":" + layer.getViewName();

            StringBuffer requestURL = new StringBuffer();
            requestURL.append(GeoserverProperties.getLocalPath() + "/wms?");
            requestURL.append("LAYERS=" + layersString);
            requestURL.append("&");
            requestURL.append("STYLES="); // there are no geoserver styles being added. sld's are used instead
            requestURL.append("&");
            requestURL.append("SRS=EPSG%3A4326");
            requestURL.append("&");
            requestURL.append("TRANSPARENT=true");
            requestURL.append("&");
            requestURL.append("ISBASELAYER=false"); // in the browser the baselayer prop is set for the 1st layer in the
                                                    // map.
            requestURL.append("&");
            requestURL.append(
                    "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&EXCEPTIONS=application%2Fvnd.ogc.se_inimage");
            requestURL.append("&");
            requestURL.append("FORMAT=image%2F" + processingFormat);
            requestURL.append("&");
            requestURL.append("BBOX=" + left + "," + bottom + "," + right + "," + top);
            requestURL.append("&");
            requestURL.append("WIDTH=" + Integer.toString(mapWidth));
            requestURL.append("&");
            requestURL.append("HEIGHT=" + Integer.toString(mapHeight));

            try {
                BufferedImage layerImg = this.getImageFromGeoserver(requestURL.toString());
                BufferedImage newOverlayBase = new BufferedImage(mapWidth, mapHeight,
                        BufferedImage.TYPE_INT_ARGB);

                newOverlayBaseGraphic = newOverlayBase.createGraphics();

                // Add transparency to the layerGraphic
                // This is set in JavaScript in the app so we are replicating browser side transparency settings that are
                // applied to the whole layer
                AlphaComposite thisLayerComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                        this.getLayerOpacity(layer));
                mapLayerGraphic2d = layerImg.createGraphics();
                newOverlayBaseGraphic.setComposite(thisLayerComposite);

                // Add the current layerGraphic to the base image
                newOverlayBaseGraphic.drawImage(layerImg, 0, 0, null);
                mapBaseGraphic.drawImage(newOverlayBase, 0, 0, null);

            } finally {
                if (newOverlayBaseGraphic != null) {
                    newOverlayBaseGraphic.dispose();
                }

                if (mapLayerGraphic2d != null) {
                    mapLayerGraphic2d.dispose();
                }
            }
            // }
        }
    } finally {
        mapBaseGraphic.dispose();
    }

    return base;
}