Example usage for java.awt.image BufferedImage getGraphics

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

Introduction

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

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:Main.java

public static BufferedImage createRotatedTextImage(String text, int angle, Font ft) {
    Graphics2D g2d = null;//ww  w  . j  a  va  2s . c o  m
    try {
        if (text == null || text.trim().length() == 0) {
            return null;
        }

        BufferedImage stringImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

        g2d = (Graphics2D) stringImage.getGraphics();
        g2d.setFont(ft);

        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D bounds = fm.getStringBounds(text, g2d);

        TextLayout tl = new TextLayout(text, ft, g2d.getFontRenderContext());

        g2d.dispose();
        g2d = null;

        return createRotatedImage(tl, (int) bounds.getWidth(), (int) bounds.getHeight(), angle);
    } catch (Exception e) {
        e.printStackTrace();

        if (g2d != null) {
            g2d.dispose();
        }
    }

    return null;
}

From source file:com.smash.revolance.ui.model.helper.ImageHelper.java

public static BufferedImage scaleImage(BufferedImage image, double widthPerCent, double heightPerCent) {
    int w = (int) (image.getWidth() * widthPerCent);
    int h = (int) (image.getHeight() * heightPerCent);
    int t = image.getType();

    Image scaledImage = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);

    BufferedImage newImg = new BufferedImage(w, h, t);
    newImg.getGraphics().drawImage(scaledImage, 0, 0, null);

    return newImg;
}

From source file:ImageUtils.java

/**
 * Scales down an image into a box of maxSideLenght x maxSideLength.
 * @param image the image to scale down. It remains untouched.
 * @param maxSideLength the maximum side length of the scaled down instance. Has to be > 0.
 * @return the scaled image, the//from  ww w.ja v a  2s.  com
 */
public static BufferedImage scaleImage(BufferedImage image, int maxSideLength) {
    assert (maxSideLength > 0);
    double originalWidth = image.getWidth();
    double originalHeight = image.getHeight();
    double scaleFactor = 0.0;
    if (originalWidth > originalHeight) {
        scaleFactor = ((double) maxSideLength / originalWidth);
    } else {
        scaleFactor = ((double) maxSideLength / originalHeight);
    }
    // create smaller image
    BufferedImage img = new BufferedImage((int) (originalWidth * scaleFactor),
            (int) (originalHeight * scaleFactor), BufferedImage.TYPE_INT_RGB);
    // fast scale (Java 1.4 & 1.5)
    Graphics g = img.getGraphics();
    g.drawImage(image, 0, 0, img.getWidth(), img.getHeight(), null);
    return img;
}

From source file:QRCode.java

public static String createQRCode(String arg) {
    int size = 125;
    String fileType = "png";
    File myFile = null;/*  w w  w.java2 s  .c o m*/
    UUID uuid = UUID.nameUUIDFromBytes(arg.getBytes());

    try {
        myFile = File.createTempFile("temp-file-name", ".png");

        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(uuid.toString(), BarcodeFormat.QR_CODE, size, size, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i++) {
            for (int j = 0; j < CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }
        ImageIO.write(image, fileType, myFile);
        //System.out.println("\n\nYou have successfully created QR Code " + myFile.getCanonicalPath());
        return myFile.getCanonicalPath();
    } catch (WriterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:davmail.util.IOUtil.java

/**
 * Resize image to a max width or height image size.
 *
 * @param inputImage input image//w w w. j  a  v a  2 s . c  o m
 * @param max        max size
 * @return scaled image
 */
public static BufferedImage resizeImage(BufferedImage inputImage, int max) {
    int width = inputImage.getWidth();
    int height = inputImage.getHeight();
    int targetWidth;
    int targetHeight;
    if (width <= max && height <= max) {
        return inputImage;
    } else if (width > height) {
        targetWidth = max;
        targetHeight = targetWidth * height / width;
    } else {
        targetHeight = max;
        targetWidth = targetHeight * width / height;
    }
    Image scaledImage = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
    BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    targetImage.getGraphics().drawImage(scaledImage, 0, 0, null);
    return targetImage;
}

From source file:SWTUtils.java

/**
 * Converts an AWT image to SWT.//from   w  ww.j  a va  2s.  com
 *
 * @param image  the image (<code>null</code> not permitted).
 *
 * @return Image data.
 */
public static ImageData convertAWTImageToSWT(Image image) {
    if (image == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return null;
    }
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return convertToSWT(bi);
}

From source file:Utils.java

/** 
 * Renders a paragraph of text (line breaks ignored) to an image (created and returned). 
 *
 * @param font The font to use//from   w  w  w.j  a va 2 s .  com
 * @param textColor The color of the text
 * @param text The message
 * @param width The width the text should be limited to
 * @return An image with the text rendered into it
 */
public static BufferedImage renderTextToImage(Font font, Color textColor, String text, int width) {
    Hashtable map = new Hashtable();
    map.put(TextAttribute.FONT, font);
    AttributedString attributedString = new AttributedString(text, map);
    AttributedCharacterIterator paragraph = attributedString.getIterator();

    FontRenderContext frc = new FontRenderContext(null, false, false);
    int paragraphStart = paragraph.getBeginIndex();
    int paragraphEnd = paragraph.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

    float drawPosY = 0;

    //First time around, just determine the height
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move it down
        drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading();
    }

    BufferedImage image = createCompatibleImage(width, (int) drawPosY);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawPosY = 0;
    lineMeasurer.setPosition(paragraphStart);
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move y-coordinate by the ascent of the layout.
        drawPosY += layout.getAscent();

        /* Compute pen x position.  If the paragraph is
           right-to-left, we want to align the TextLayouts
           to the right edge of the panel.
         */
        float drawPosX;
        if (layout.isLeftToRight()) {
            drawPosX = 0;
        } else {
            drawPosX = width - layout.getAdvance();
        }

        // Draw the TextLayout at (drawPosX, drawPosY).
        layout.draw(graphics, drawPosX, drawPosY);

        // Move y-coordinate in preparation for next layout.
        drawPosY += layout.getDescent() + layout.getLeading();
    }

    graphics.dispose();
    return image;
}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static void copyImage(BufferedImage src, BufferedImage image) {
    Graphics2D g = (Graphics2D) image.getGraphics();
    int w = image.getWidth();
    int h = image.getHeight();
    g.drawImage(src, 0, 0, w, h, null);/*w  w  w  .j  av  a 2s  .  c  o  m*/
    src.flush();
}

From source file:ImageUtilities.java

private static BufferedImage convertToARGB(BufferedImage srcImage) {
    BufferedImage newImage = new BufferedImage(srcImage.getWidth(null), srcImage.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics bg = newImage.getGraphics();
    bg.drawImage(srcImage, 0, 0, null);/*from   ww w  . j a  v a 2  s  .  c  o  m*/
    bg.dispose();
    return newImage;
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdDumper.java

public static void displayGraph(String metricName, String rrdFilename, long startTime, long endTime,
        String verticalAxisLabel, String title) throws IOException, MetricsGraphException {
    // Create RRD DB in read-only mode for the specified RRD file
    RrdDb rrdDb = new RrdDb(rrdFilename, true);

    // Extract the data source (should always only be one data source per RRD file - otherwise
    // we have a problem)
    if (rrdDb.getDsCount() != 1) {
        throw new MetricsGraphException("Only one data source per RRD file is supported - RRD file "
                + rrdFilename + " has " + rrdDb.getDsCount() + " data sources.");
    }/*from  w w w  .j  ava2  s. c o  m*/

    // Define attributes of the graph to be created for this metric
    RrdGraphDef graphDef = new RrdGraphDef();
    graphDef.setTimeSpan(startTime, endTime);
    graphDef.setImageFormat("PNG");
    graphDef.setShowSignature(false);
    graphDef.setStep(60);
    graphDef.setVerticalLabel(verticalAxisLabel);
    graphDef.setHeight(500);
    graphDef.setWidth(1000);
    graphDef.setTitle(title);

    DsType dataSourceType = rrdDb.getDatasource(0).getType();

    // Determine if the Data Source for this RRD file is a COUNTER or GAUGE
    // (Need to know this because COUNTER data is averaged across samples and the vertical axis
    // of the
    // generated graph by default will show data per rrdStep interval)
    if (dataSourceType == DsType.DERIVE) {
        long rrdStep = rrdDb.getRrdDef().getStep();

        // Multiplied by the rrdStep to "undo" the automatic averaging that RRD does
        // when it collects TOTAL data - we want the actual totals for the step, not
        // the average of the totals.
        graphDef.datasource("myTotal", rrdFilename, "data", ConsolFun.TOTAL);
        graphDef.datasource("realTotal", "myTotal," + rrdStep + ",*");
        graphDef.datasource("validTotal", "realTotal," + METRICS_MAX_THRESHOLD + ",GT,UNKN,realTotal,IF");
        graphDef.line("validTotal", Color.BLUE, convertCamelCase(metricName), 2);

        // Add some spacing between the graph and the summary stats shown beneath the graph
        graphDef.comment("\\s");
        graphDef.comment("\\s");
        graphDef.comment("\\c");

        // Average, Min, and Max over all of the TOTAL data - displayed at bottom of the graph
        graphDef.gprint("validTotal", ConsolFun.AVERAGE, "Average = %.3f%s");
        graphDef.gprint("validTotal", ConsolFun.MIN, "Min = %.3f%s");
        graphDef.gprint("validTotal", ConsolFun.MAX, "Max = %.3f%s");
    } else if (dataSourceType == DsType.GAUGE) {
        graphDef.datasource("myAverage", rrdFilename, "data", ConsolFun.AVERAGE);
        graphDef.line("myAverage", Color.RED, convertCamelCase(metricName), 2);

        // Add some spacing between the graph and the summary stats shown beneath the graph
        graphDef.comment("\\s");
        graphDef.comment("\\s");
        graphDef.comment("\\c");

        // Average, Min, and Max over all of the AVERAGE data - displayed at bottom of the graph
        graphDef.gprint("myAverage", ConsolFun.AVERAGE, "Average = %.3f%s");
        graphDef.gprint("myAverage", ConsolFun.MIN, "Min = %.3f%s");
        graphDef.gprint("myAverage", ConsolFun.MAX, "Max = %.3f%s");
    } else {
        rrdDb.close();
        throw new MetricsGraphException("Unsupported data source type " + dataSourceType.name()
                + " in RRD file " + rrdFilename + ", only COUNTER and GAUGE data source types supported.");
    }

    rrdDb.close();

    // Use "-" as filename so that RRD creates the graph only in memory (no file is
    // created, hence no file locking problems due to race conditions between multiple clients)
    graphDef.setFilename("graph.gif");
    RrdGraph graph = new RrdGraph(graphDef);
    BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    graph.render(bi.getGraphics());
}