Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:net.rptools.lib.image.ThumbnailManager.java

private Image createThumbnail(File file) throws IOException {
    // Gather info
    File thumbnailFile = getThumbnailFile(file);
    if (thumbnailFile.exists()) {
        return ImageUtil.getImage(thumbnailFile);
    }//  w  w  w .jav  a2 s . co  m

    Image image = ImageUtil.getImage(file);
    Dimension imgSize = new Dimension(image.getWidth(null), image.getHeight(null));

    // Test if we Should we bother making a thumbnail ?
    // Jamz: New size 100k (was 30k) and put in check so we're not creating thumbnails LARGER than the original...
    if (file.length() < 102400
            || (imgSize.width <= thumbnailSize.width && imgSize.height <= thumbnailSize.height)) {
        return image;
    }
    // Transform the image
    SwingUtil.constrainTo(imgSize, Math.min(image.getWidth(null), thumbnailSize.width),
            Math.min(image.getHeight(null), thumbnailSize.height));
    BufferedImage thumbnailImage = new BufferedImage(imgSize.width, imgSize.height,
            ImageUtil.pickBestTransparency(image));

    Graphics2D g = thumbnailImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.drawImage(image, 0, 0, imgSize.width, imgSize.height, null);
    g.dispose();

    // Use png to preserve transparency
    FileUtils.writeByteArrayToFile(thumbnailFile, ImageUtil.imageToBytes(thumbnailImage, "png"));

    return thumbnailImage;
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

@Override
public BufferedImage createCaptcha(char[] text) {
    if (text == null || text.length == 0) {
        throw new IllegalArgumentException("No captcha text given");
    }/*from w w w . j  ava2s . c o m*/

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setBackground(Color.WHITE);
    g2d.setColor(Color.BLACK);

    clearCanvas(g2d);

    if (showGrid) {
        drawGrid(g2d);
    }

    int charMaxWidth = width / text.length;
    int xPos = 0;
    for (char ch : text) {
        drawCharacter(g2d, ch, xPos, charMaxWidth);
        xPos += charMaxWidth;
    }

    g2d.dispose();
    return image;
}

From source file:com.t3.image.ThumbnailManager.java

private Image createThumbnail(File file) throws IOException {

    // Gather info
    File thumbnailFile = getThumbnailFile(file);
    if (thumbnailFile.exists()) {
        return ImageUtil.getImage(thumbnailFile);
    }//  w  w w.  ja v a2  s.co  m

    Image image = ImageUtil.getImage(file);

    // Should we bother making a thumbnail ?
    if (file.length() < 30 * 1024) {
        return image;
    }

    // Transform the image
    Dimension imgSize = new Dimension(image.getWidth(null), image.getHeight(null));
    SwingUtil.constrainTo(imgSize, thumbnailSize.width, thumbnailSize.height);

    BufferedImage thumbnailImage = new BufferedImage(imgSize.width, imgSize.height,
            ImageUtil.pickBestTransparency(image));

    Graphics2D g = thumbnailImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.drawImage(image, 0, 0, imgSize.width, imgSize.height, null);
    g.dispose();

    // Ensure path exists
    if (thumbnailFile.exists())
        thumbnailFile.delete();
    else
        thumbnailFile.getParentFile().mkdirs();

    try (OutputStream os = new FileOutputStream(thumbnailFile)) {
        IOUtils.write(ImageUtil.imageToBytes(thumbnailImage, "png"), os);
    }

    return thumbnailImage;
}

From source file:org.n52.server.io.DiagramGenerator.java

public void createLegend(DesignOptions options, OutputStream out) throws OXFException, IOException {

    int topMargin = 10;
    int leftMargin = 30;
    int iconWidth = 15;
    int iconHeight = 15;
    int verticalSpaceBetweenEntries = 20;
    int horizontalSpaceBetweenIconAndText = 15;

    DesignDescriptionList ddList = buildUpDesignDescriptionList(options);
    int width = 800;
    int height = topMargin + (ddList.size() * (iconHeight + verticalSpaceBetweenEntries));

    BufferedImage legendImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D legendGraphics = legendImage.createGraphics();
    legendGraphics.setColor(Color.white);
    legendGraphics.fillRect(0, 0, width, height);

    int offset = 0;
    for (RenderingDesign dd : ddList.getAllDesigns()) {
        int yPos = topMargin + offset * iconHeight + offset * verticalSpaceBetweenEntries;

        // icon:/*from  ww w .  ja  v  a 2 s  . c  o  m*/
        legendGraphics.setColor(dd.getColor());
        legendGraphics.fillRect(leftMargin, yPos, iconWidth, iconHeight);

        // text:
        legendGraphics.setColor(Color.black);

        legendGraphics.drawString(dd.getFeature().getLabel() + " - " + dd.getLabel(),
                leftMargin + iconWidth + horizontalSpaceBetweenIconAndText, yPos + iconHeight);

        offset++;
    }

    JPEGImageWriteParam p = new JPEGImageWriteParam(null);
    p.setCompressionMode(JPEGImageWriteParam.MODE_DEFAULT);
    write(legendImage, FORMAT, out);
}

From source file:Composite.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    Dimension d = getSize();//  w w w  . j a  v a  2  s  . c  o m
    int w = d.width;
    int h = d.height;

    // Creates the buffered image.
    BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gbi = buffImg.createGraphics();

    // Clears the previously drawn image.
    g2.setColor(Color.white);
    g2.fillRect(0, 0, d.width, d.height);

    int rectx = w / 4;
    int recty = h / 4;

    // Draws the rectangle and ellipse into the buffered image.
    gbi.setColor(new Color(0.0f, 0.0f, 1.0f, 1.0f));
    gbi.fill(new Rectangle2D.Double(rectx, recty, 150, 100));
    gbi.setColor(new Color(1.0f, 0.0f, 0.0f, 1.0f));
    gbi.setComposite(ac);
    gbi.fill(new Ellipse2D.Double(rectx + rectx / 2, recty + recty / 2, 150, 100));

    // Draws the buffered image.
    g2.drawImage(buffImg, null, 0, 0);
}

From source file:org.n52.oxf.render.sos.TimeSeriesChartRenderer.java

/**
 * The resulting IVisualization shows a chart which consists a TimeSeries for each FeatureOfInterest
 * contained in the observationCollection.
 *//*from ww  w  .  j a v  a 2 s. com*/
public IVisualization renderChart(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int width, int height) {
    JFreeChart chart = renderChart(observationCollection, paramCon);

    Plot plot = chart.getPlot();

    // draw plot into image:

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);

    plot.draw(g, new Rectangle2D.Float(0, 0, width, height), null, null, null);

    return new StaticVisualization(image);
}

From source file:edu.kit.dama.ui.components.TextImage.java

/**
 * Get the bytes of the final image./*w  w  w.  j  ava 2s.  c o  m*/
 *
 * @return The byte array containing the bytes of the resulting image.
 *
 * @throws IOException if creating the image fails.
 */
public byte[] getBytes() throws IOException {
    Image transparentImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(
            new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB).getSource(), new RGBImageFilter() {
                @Override
                public final int filterRGB(int x, int y, int rgb) {
                    return (rgb << 8) & 0xFF000000;
                }
            }));

    //create the actual image and overlay it by the transparent background
    BufferedImage outputImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = outputImage.createGraphics();
    g2d.drawImage(transparentImage, 0, 0, null);
    //draw the remaining stuff
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.setColor(color);
    g2d.fillRoundRect(0, 0, size, size, 20, 20);
    g2d.setColor(new Color(Math.round((float) color.getRed() * .9f), Math.round((float) color.getGreen() * .9f),
            Math.round((float) color.getBlue() * .9f)));
    g2d.drawRoundRect(0, 0, size - 1, size - 1, 20, 20);

    Font font = new Font("Dialog", Font.BOLD, size - 4);
    g2d.setFont(font);
    g2d.setColor(Color.WHITE);

    String s = text.toUpperCase().substring(0, 1);
    FontMetrics fm = g2d.getFontMetrics();
    float x = ((float) size - (float) fm.stringWidth(s)) / 2f;
    float y = ((float) fm.getAscent()
            + (float) ((float) size - ((float) fm.getAscent() + (float) fm.getDescent())) / 2f) - 1f;
    g2d.drawString(s, x, y);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ImageIO.write(outputImage, "png", bout);
    g2d.dispose();
    return bout.toByteArray();
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public BufferedImage rasterize(final int imageType) throws IOException {
    final int svgWidth = Math.round(getSVGWidth());
    final int svgHeight = Math.round(getSVGHeight());

    final BufferedImage result = new BufferedImage(svgWidth, svgHeight, imageType);
    final Graphics2D g = result.createGraphics();

    processAntialias(this.quality, g);
    this.svgGraphicsNode.primitivePaint(g);

    g.dispose();//www.ja va  2  s  .  co  m
    return result;
}

From source file:Paints.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Paint the entire background using a GradientPaint.
    // The background color varies diagonally from deep red to pale blue
    g.setPaint(new GradientPaint(0, 0, new Color(150, 0, 0), WIDTH, HEIGHT, new Color(200, 200, 255)));
    g.fillRect(0, 0, WIDTH, HEIGHT); // fill the background

    // Use a different GradientPaint to draw a box.
    // This one alternates between deep opaque green and transparent green.
    // Note: the 4th arg to Color() constructor specifies color opacity
    g.setPaint(new GradientPaint(0, 0, new Color(0, 150, 0), 20, 20, new Color(0, 150, 0, 0), true));
    g.setStroke(new BasicStroke(15)); // use wide lines
    g.drawRect(25, 25, WIDTH - 50, HEIGHT - 50); // draw the box

    // The glyphs of fonts can be used as Shape objects, which enables
    // us to use Java2D techniques with letters Just as we would with
    // any other shape. Here we get some letter shapes to draw.
    Font font = new Font("Serif", Font.BOLD, 10); // a basic font
    Font bigfont = // a scaled up version
            font.deriveFont(AffineTransform.getScaleInstance(30.0, 30.0));
    GlyphVector gv = bigfont.createGlyphVector(g.getFontRenderContext(), "JAV");
    Shape jshape = gv.getGlyphOutline(0); // Shape of letter J
    Shape ashape = gv.getGlyphOutline(1); // Shape of letter A
    Shape vshape = gv.getGlyphOutline(2); // Shape of letter V

    // We're going to outline the letters with a 5-pixel wide line
    g.setStroke(new BasicStroke(5.0f));

    // We're going to fake shadows for the letters using the
    // following Paint and AffineTransform objects
    Paint shadowPaint = new Color(0, 0, 0, 100); // Translucent black
    AffineTransform shadowTransform = AffineTransform.getShearInstance(-1.0, 0.0); // Shear to the right
    shadowTransform.scale(1.0, 0.5); // Scale height by 1/2

    // Move to the baseline of our first letter
    g.translate(65, 270);/* w ww.j  ava  2  s.c o  m*/

    // Draw the shadow of the J shape
    g.setPaint(shadowPaint);
    g.translate(15, 20); // Compensate for the descender of the J
    // transform the J into the shape of its shadow, and fill it
    g.fill(shadowTransform.createTransformedShape(jshape));
    g.translate(-15, -20); // Undo the translation above

    // Now fill the J shape with a solid (and opaque) color
    g.setPaint(Color.blue); // Fill with solid, opaque blue
    g.fill(jshape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(jshape); // And draw the outline of the J

    // Now draw the A shadow
    g.translate(75, 0); // Move to the right
    g.setPaint(shadowPaint); // Set shadow color
    g.fill(shadowTransform.createTransformedShape(ashape)); // draw shadow

    // Draw the A shape using a solid transparent color
    g.setPaint(new Color(0, 255, 0, 125)); // Transparent green as paint
    g.fill(ashape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid back
    g.draw(ashape); // Draw the outline

    // Move to the right and draw the shadow of the letter V
    g.translate(175, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(vshape));

    // We're going to fill the next letter using a TexturePaint, which
    // repeatedly tiles an image. The first step is to obtain the image.
    // We could load it from an image file, but here we create it
    // ourselves by drawing a into an off-screen image. Note that we use
    // a GradientPaint to fill the off-screen image, so the fill pattern
    // combines features of both Paint classes.
    BufferedImage tile = // Create an image
            new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D tg = tile.createGraphics(); // Get its Graphics for drawing
    tg.setColor(Color.pink);
    tg.fillRect(0, 0, 50, 50); // Fill tile background with pink
    tg.setPaint(new GradientPaint(40, 0, Color.green, // diagonal gradient
            0, 40, Color.gray)); // green to gray
    tg.fillOval(5, 5, 40, 40); // Draw a circle with this gradient

    // Use this new tile to create a TexturePaint and fill the letter V
    g.setPaint(new TexturePaint(tile, new Rectangle(0, 0, 50, 50)));
    g.fill(vshape); // Fill letter shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(vshape); // Draw outline of letter

    // Move to the right and draw the shadow of the final A
    g.translate(160, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(ashape));

    g.fill(ashape); // Fill letter A
    g.setPaint(Color.black); // Revert to solid black
    g.draw(ashape); // Draw the outline of the A
}

From source file:org.n52.server.sos.generator.DiagramGenerator.java

/**
 * Creates a time series chart diagram and writes it to the OutputStream.
 * //from   w w w  .ja  va2 s  .co  m
 * @param entireCollMap
 * @param options
 * @param out
 * @throws OXFException
 * @throws IOException
 */
public void producePresentation(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        FileOutputStream out, boolean compress) throws OXFException, IOException {

    // render features:
    int width = options.getWidth();
    int height = options.getHeight();
    Calendar begin = Calendar.getInstance();
    begin.setTimeInMillis(options.getBegin());
    Calendar end = Calendar.getInstance();
    end.setTimeInMillis(options.getEnd());

    DiagramRenderer renderer = new DiagramRenderer(false);

    JFreeChart diagramChart = renderer.renderChart(entireCollMap, options, begin, end, compress);
    diagramChart.removeLegend();

    // draw chart into image:
    BufferedImage diagramImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = diagramImage.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);

    diagramChart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));

    JPEGEncodeParam p = new JPEGEncodeParam();
    p.setQuality(1f);
    ImageEncoder encoder = ImageCodec.createImageEncoder("jpeg", out, p);

    encoder.encode(diagramImage);
}