Example usage for java.awt Graphics2D dispose

List of usage examples for java.awt Graphics2D dispose

Introduction

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

Prototype

public abstract void dispose();

Source Link

Document

Disposes of this graphics context and releases any system resources that it is using.

Usage

From source file:Main.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(Color.RED);/*w w w.  j a v a2 s  .  co  m*/
    g2d.drawLine(0, 0, getWidth(), getHeight());
    g2d.drawLine(getWidth(), 0, 0, getHeight());
    g2d.dispose();
}

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 {/* w  w  w .ja  va  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.pkhsolutions.pecsapp.control.PictureTransformer.java

/**
 * TODO Document me/*from ww w . j  a v  a2 s.c  o m*/
 *
 * @param image
 * @param maxHeightInPx
 * @param maxWidthInPx
 * @return
 */
@NotNull
public BufferedImage scaleIfNecessary(@NotNull BufferedImage image, int maxHeightInPx, int maxWidthInPx) {
    int w = image.getWidth();
    int h = image.getHeight();

    int newW;
    int newH;

    if (w <= maxWidthInPx && h <= maxHeightInPx) {
        return image;
    } else if (w > h) {
        newW = maxWidthInPx;
        newH = newW * h / w;
    } else {
        newH = maxHeightInPx;
        newW = newH * w / h;
    }
    LOGGER.info("Original size was w{} x h{}, new size is w{} x h{}", w, h, newW, newH);
    Image tmp = image.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage img = new BufferedImage(newW, newH, image.getType());
    Graphics2D g2d = img.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return img;
}

From source file:Main.java

public MyPanel() {
    this.setLayout(new GridLayout());
    this.setPreferredSize(new Dimension(W, H));
    int w = W / 2;
    int h = H / 2;
    int r = w / 5;
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setColor(Color.gray);/*from w ww . j  a  va  2 s  .co  m*/
    g.fillRect(0, 0, w, h);
    g.setColor(Color.blue);
    g.fillRect(w / 2 - r, h / 2 - r / 2, 2 * r, r);
    g.dispose();
    this.add(new JLabel(new ImageIcon(bi), JLabel.CENTER));
}

From source file:Myopia.java

@Override
public void paint(Graphics g, JComponent c) {
    int w = c.getWidth();
    int h = c.getHeight();

    if (w == 0 || h == 0) {
        return;/*from w w w.  ja v a2s  .c o m*/
    }

    // Only create the offscreen image if the one we have
    // is the wrong size.
    if (mOffscreenImage == null || mOffscreenImage.getWidth() != w || mOffscreenImage.getHeight() != h) {
        mOffscreenImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    }

    Graphics2D ig2 = mOffscreenImage.createGraphics();
    ig2.setClip(g.getClip());
    super.paint(ig2, c);
    ig2.dispose();

    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(mOffscreenImage, mOperation, 0, 0);
}

From source file:com.piaoyou.util.ImageUtil.java

/**
 * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep
 *          inputStream xuong thumbnailFile luon
 *
 * This method create a thumbnail and reserve the ratio of the output image
 * NOTE: This method closes the inputStream after it have done its work.
 *
 * @param inputStream     the stream of a jpeg file
 * @param outputStream    the output stream
 * @param maxWidth        the maximum width of the image
 * @param maxHeight       the maximum height of the image
 * @throws IOException//from ww  w .j a  va2s .  c  om
 * @throws BadInputException
 */
public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth,
        int maxHeight) throws IOException {

    if (inputStream == null) {
        throw new IllegalArgumentException("inputStream must not be null.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("outputStream must not be null.");
    }

    //boolean useSun = false;
    if (maxWidth <= 0) {
        throw new IllegalArgumentException("maxWidth must >= 0");
    }
    if (maxHeight <= 0) {
        throw new IllegalArgumentException("maxHeight must >= 0");
    }

    try {
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream);
        //BufferedImage srcImage = decoder.decodeAsBufferedImage();
        byte[] srcByte = FileUtil.getBytes(inputStream);
        InputStream is = new ByteArrayInputStream(srcByte);
        //ImageIcon imageIcon = new ImageIcon(srcByte);
        //Image srcImage = imageIcon.getImage();

        BufferedImage srcImage = ImageIO.read(is);
        if (srcImage == null) {
            throw new IOException("Cannot decode image. Please check your file again.");
        }

        int imgWidth = srcImage.getWidth();
        int imgHeight = srcImage.getHeight();
        //          imgWidth or imgHeight could be -1, which is considered as an assertion
        AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0),
                "Assertion: ImageUtil: cannot get the image size.");
        // Set the scale.
        AffineTransform tx = new AffineTransform();
        if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) {
            double scaleX = (double) maxWidth / imgWidth;
            double scaleY = (double) maxHeight / imgHeight;
            double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY;
            imgWidth = (int) (imgWidth * scaleX);
            imgWidth = (imgWidth == 0) ? 1 : imgWidth;
            imgHeight = (int) (imgHeight * scaleY);
            imgHeight = (imgHeight == 0) ? 1 : imgHeight;
            // scale as needed
            tx.scale(scaleRatio, scaleRatio);
        } else {// we don't need any transform here, just save it to file and return
            outputStream.write(srcByte);
            return;
        }

        // create thumbnail image
        BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bufferedImage.createGraphics();
        boolean useTransform = false;
        if (useTransform) {// use transfrom to draw
            //log.trace("use transform");
            g.drawImage(srcImage, tx, null);
        } else {// use java filter
            //log.trace("use filter");
            Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight);
            g.drawImage(scaleImage, 0, 0, null);
        }
        g.dispose();// free resource
        // write it to outputStream 
        // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
        // encoder.encode(bufferedImage);

        ImageIO.write(bufferedImage, "jpeg", outputStream);
    } catch (IOException e) {
        log.error("Error", e);
        throw e;
    } finally {// this finally is very important
        try {
            inputStream.close();
        } catch (IOException e) {
            /* ignore */
            e.printStackTrace();
        }
        try {
            outputStream.close();
        } catch (IOException e) {/* ignore */
            e.printStackTrace();
        }
    }
}

From source file:Main.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(Color.RED);/*from   w w  w . j a v  a2  s .  co m*/
    g2d.fill(poly);

    g2d.setColor(Color.GREEN);
    g2d.translate(50, 100);
    g2d.fill(triangleShape);
    g2d.dispose();
}

From source file:Main.java

public void createThumbnail(File file) throws Exception {
    BufferedImage img = ImageIO.read(file);
    BufferedImage thumb = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = (Graphics2D) thumb.getGraphics();
    g2d.drawImage(img, 0, 0, thumb.getWidth() - 1, thumb.getHeight() - 1, 0, 0, img.getWidth() - 1,
            img.getHeight() - 1, null);/*from  w  ww . j a v a2s  .co  m*/
    g2d.dispose();
    ImageIO.write(thumb, "PNG", new File("thumb.png"));
}

From source file:BasicShapes.java

public void paint(Graphics g) {
    BufferedImage bimage = new BufferedImage(200, 200, BufferedImage.TYPE_BYTE_INDEXED);
    Graphics2D g2d = bimage.createGraphics();

    Color transparent = new Color(0, 0, 0, 0);
    g2d.setColor(transparent);//from   ww w  .  ja  v a2  s  .  c  om
    g2d.setComposite(AlphaComposite.Src);
    g2d.fill(new Rectangle2D.Float(20, 20, 100, 20));
    g2d.dispose();

}

From source file:business.model.CaptchaModel.java

/**
 *
 * @param baseImage/*from  w ww .  j a  v  a 2  s.  c o m*/
 * @return
 */
private static BufferedImage getDistortedImage(BufferedImage baseImage) {
    BufferedImage distortedImage = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);

    Graphics2D graph = (Graphics2D) distortedImage.getGraphics();

    ShadowFilter shadowFilter = new ShadowFilter();
    shadowFilter.setRadius(10);
    shadowFilter.setDistance(5);
    shadowFilter.setOpacity(1);

    Random rand = new Random();

    RippleFilter rippleFilter = new RippleFilter();
    rippleFilter.setWaveType(RippleFilter.SINE);
    rippleFilter.setXAmplitude(1.6f);
    rippleFilter.setYAmplitude(1.0f);
    rippleFilter.setXWavelength(5);
    rippleFilter.setYWavelength(2);
    rippleFilter.setEdgeAction(TransformFilter.BILINEAR);

    BufferedImage effectImage = rippleFilter.filter(baseImage, null);
    effectImage = shadowFilter.filter(effectImage, null);

    graph.drawImage(effectImage, 0, 0, null, null);
    graph.dispose();

    // draw lines over the image and/or text
    //      noiseProducer.makeNoise(distortedImage, .1f, .1f, .25f, .25f);
    return distortedImage;
}