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:org.wkm.mtool.service.QRCodeService.java

/**
 * ??(QRCode)//from  w  w w. j  a va 2  s . co  m
 * @param content
 * @param imgFile
 */
private void encoderQRCode(String content, File imgFile) {
    try {
        Qrcode qrcodeHandler = new Qrcode();
        qrcodeHandler.setQrcodeErrorCorrect('M');
        qrcodeHandler.setQrcodeEncodeMode('B');
        qrcodeHandler.setQrcodeVersion(7);

        System.out.println(content);
        byte[] contentBytes = content.getBytes(Consts.UTF_8.name());

        BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufImg.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.clearRect(0, 0, 140, 140);

        // ? > BLACK
        gs.setColor(Color.BLACK);

        // ??? ???
        int pixoff = 2;
        //  > ?
        if (contentBytes.length > 0 && contentBytes.length < 120) {
            boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        } else {
            System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
        }

        gs.dispose();
        bufImg.flush();

        // ??QRCode
        ImageIO.write(bufImg, "png", imgFile);

    } catch (Exception e) {
        log.info("Exception:" + e.getMessage());
    }
}

From source file:net.sf.jabref.gui.PdfPreviewPanel.java

private BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) {
    int h = originalImage.getHeight();
    int w = originalImage.getWidth();
    if ((height == 0) || (width == 0)) {
        height = h;//from   w  w w. j  ava 2s.c om
        width = w;
    } else {
        float factorH = (float) height / (float) h;
        float factorW = (float) width / (float) w;

        if (factorH < factorW) {
            // use factorH, only width has to be changed as height is
            // already correct
            width = Math.round(w * factorH);
        } else {
            width = Math.round(h * factorW);
        }
    }

    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, width, height, null);
    return resizedImage;
}

From source file:ch.fork.AdHocRailway.ui.utils.ImageTools.java

private BufferedImage ImageToBufferedImage(Image image, int width, int height) {
    BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(image, 0, 0, null);/*from  w  w w  .j  a  v a  2s.c om*/
    g2.dispose();
    return dest;
}

From source file:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportComponent()./*from  w  w w .j a v a  2  s .  co m*/
 *
 * @param exportable
 * @param filename
 * @param timestamp
 * @param type
 * @param width
 * @param height
 * @param log
 * @param clock
 *
 * @return boolean
 */

public static boolean exportComponent(final ExportableComponentInterface exportable, final String filename,
        final boolean timestamp, final String type, final int width, final int height, final Vector<Vector> log,
        final ObservatoryClockInterface clock) {
    final String SOURCE = "DataExporter.exportComponent()";
    boolean boolSuccess;

    //        String[] arrayNames = ImageIO.getWriterFormatNames();
    //
    //        for (int i = 0;
    //             i < arrayNames.length;
    //             i++)
    //            {
    //            String arrayName = arrayNames[i];
    //            System.out.println("DataExporter.exportComponent() FORMAT NAME=" + arrayName);
    //            }
    //
    boolSuccess = false;

    if ((exportable != null) && (filename != null) && (!EMPTY_STRING.equals(filename)) && (type != null)
            && (!EMPTY_STRING.equals(type)) && (log != null) && (clock != null)
            && (Arrays.asList(ImageIO.getWriterFormatNames()).contains(type))) {
        try {
            final File file;
            final int intRealWidth;
            final int intRealHeight;

            file = new File(FileUtilities.buildFullFilename(filename, timestamp, type));
            FileUtilities.overwriteFile(file);

            intRealWidth = width;
            intRealHeight = height;

            // Support all current formats
            if ((FileUtilities.png.equalsIgnoreCase(type)) || (FileUtilities.jpg.equalsIgnoreCase(type))
                    || (FileUtilities.gif.equalsIgnoreCase(type))) {
                BufferedImage buffer;
                final Graphics2D graphics2D;

                LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(),
                        "DataExporter.exportComponent() writing [file " + file.getAbsolutePath() + "] [width="
                                + intRealWidth + "] [height=" + intRealHeight + "]");

                buffer = new BufferedImage(intRealWidth, intRealHeight, BufferedImage.TYPE_INT_RGB);

                // Create a graphics context on the buffered image
                graphics2D = buffer.createGraphics();

                // Draw on the image
                graphics2D.clearRect(0, 0, intRealWidth, intRealHeight);
                exportable.paintForExport(graphics2D, intRealWidth, intRealHeight);

                // Export the image
                ImageIO.write(buffer, type, file);
                graphics2D.dispose();
                boolSuccess = true;

                SimpleEventLogUIComponent
                        .logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                // Help the GC?
                buffer = null;

                ObservatoryInstrumentHelper.runGarbageCollector();
            } else {
                SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT
                        + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_INVALID_FORMAT + TERMINATOR, SOURCE,
                        clock);
            }
        }

        catch (IllegalArgumentException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT
                            + EXCEPTION_PARAMETER_INVALID + TERMINATOR + SPACE + METADATA_EXCEPTION
                            + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (FileNotFoundException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (IOException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }
    } else {
        SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT
                + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_COMPONENT + TERMINATOR, SOURCE, clock);
    }

    return (boolSuccess);
}

From source file:costumetrade.common.verify.ImageVerification.java

public Pair<String, BufferedImage> create() {
    int x = 0, fontHeight = 0, codeY = 0;
    int red = 0, green = 0, blue = 0;

    x = width / (codeCount + 2);//?
    fontHeight = height - 2;//
    codeY = height - 4;/*from ww  w  .  ja va  2 s  . co m*/

    // ?buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buffImg.createGraphics();
    // ?
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    // 
    g.setFont(new Font("Arial", Font.PLAIN, fontHeight));

    for (int i = 0; i < lineCount; i++) {

        int xs = RandomUtils.nextInt(0, width);
        int ys = RandomUtils.nextInt(0, height);
        int xe = xs + RandomUtils.nextInt(0, width / 8);
        int ye = ys + RandomUtils.nextInt(0, height / 8);
        red = RandomUtils.nextInt(0, 255);
        green = RandomUtils.nextInt(0, 255);
        blue = RandomUtils.nextInt(0, 255);
        g.setColor(new Color(red, green, blue));
        g.drawLine(xs, ys, xe, ye);
    }

    // randomCode???
    StringBuilder randomCode = new StringBuilder();
    // ?codeCount??
    for (int i = 0; i < codeCount; i++) {
        String strRand = String.valueOf(codeSequence[RandomUtils.nextInt(0, codeSequence.length)]);
        // ????
        red = RandomUtils.nextInt(0, 255);
        green = RandomUtils.nextInt(0, 255);
        blue = RandomUtils.nextInt(0, 255);
        g.setColor(new Color(red, green, blue));
        g.drawString(strRand, (i + 1) * x, codeY);
        // ??
        randomCode.append(strRand);
    }
    // ????Session
    return new Pair<String, BufferedImage>(randomCode.toString(), buffImg);
}

From source file:fi.helsinki.opintoni.service.ImageService.java

private BufferedImage toJpg(BufferedImage bufferedImage) {
    BufferedImage jpgImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    jpgImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.BLACK, null);
    return jpgImage;
}

From source file:doge.photo.DogePhotoManipulator.java

private void render(BufferedImage sourceImage, BufferedImage destinationImage) {
    Graphics2D destinationGraphics = destinationImage.createGraphics();
    try {/* w  ww. j a  va2s . c o m*/
        setGraphicsHints(destinationGraphics);
        renderBackground(sourceImage, destinationImage, destinationGraphics);
        renderOverlay(destinationImage, destinationGraphics);
    } finally {
        destinationGraphics.dispose();
    }
}

From source file:com.igormaznitsa.jhexed.values.HexSVGImageValue.java

@Override
public void prerasterizeIcon(final Shape shape) {
    try {/*from w  ww .  j  a  v a2  s .  c  o m*/
        final Rectangle r = shape.getBounds();
        final BufferedImage img = this.image.rasterize(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
        final BufferedImage result = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = result.createGraphics();
        g.setClip(shape);
        g.drawImage(img, 0, 0, null);
        g.dispose();
        this.prerasterized = result;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:AttributesApp.java

public AttributesApp() {
    setBackground(Color.lightGray);
    setSize(500, 200);/*from  ww  w.  ja va 2  s  . c o m*/

    attribString = new AttributedString(text);

    GeneralPath star = new GeneralPath();
    star.moveTo(0, 0);
    star.lineTo(10, 30);
    star.lineTo(-10, 10);
    star.lineTo(10, 10);
    star.lineTo(-10, 30);
    star.closePath();
    GraphicAttribute starShapeAttr = new ShapeGraphicAttribute(star, GraphicAttribute.TOP_ALIGNMENT, false);
    attribString.addAttribute(TextAttribute.CHAR_REPLACEMENT, starShapeAttr, 0, 1);
    attribString.addAttribute(TextAttribute.FOREGROUND, new Color(255, 255, 0), 0, 1);

    int index = text.indexOf("Java Source");
    attribString.addAttribute(TextAttribute.FOREGROUND, Color.blue, index, index + 7);
    Font font = new Font("sanserif", Font.ITALIC, 40);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 7);

    loadImage();
    BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D big = bimage.createGraphics();
    big.drawImage(image, null, this);
    GraphicAttribute javaImageAttr = new ImageGraphicAttribute(bimage, GraphicAttribute.TOP_ALIGNMENT, 0, 0);

    index = text.indexOf("Java");
    attribString.addAttribute(TextAttribute.CHAR_REPLACEMENT, javaImageAttr, index - 1, index);

    font = new Font("serif", Font.BOLD, 60);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 4);
    attribString.addAttribute(TextAttribute.FOREGROUND, new Color(243, 63, 163), index, index + 4); // Start and end indexes.

    index = text.indexOf("source");
    attribString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, index, index + 2);

    index = text.indexOf("and support");
    font = new Font("sanserif", Font.ITALIC, 40);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 10);

    attribString.addAttribute(TextAttribute.FOREGROUND, Color.white, index, index + 2); // Start and end indexes.
    attribString.addAttribute(TextAttribute.FOREGROUND, Color.blue, index + 3, index + 10); // Start and end indexes.
}

From source file:org.geotools.renderer.chart.ChartGraphicFactory.java

BufferedImage drawChart(JFreeChart chart, int w, int h) {
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D gr = bi.createGraphics();
    try {/*from w ww  . jav a2s  .c  o  m*/
        chart.draw(gr, new Rectangle2D.Double(0, 0, w, h));
    } finally {
        gr.dispose();
    }

    return bi;
}