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:com.formkiq.core.service.conversion.PdfToPngFormatConverter.java

/**
 * Merge Buffered Images together./*from  ww w  .j  ava 2 s .  c o  m*/
 * @param buffImages {@link BufferedImage}
 * @return {@link ConversionResult}
 * @throws IOException IOException
 */
private ConversionResult merge(final BufferedImage[] buffImages) throws IOException {

    ConversionResult result = new ConversionResult();

    int cols = 1;
    int rows = buffImages.length;

    int type = buffImages[0].getType();
    int width = buffImages[0].getWidth();
    int height = buffImages[0].getHeight();

    BufferedImage bi = new BufferedImage(width * cols, height * rows, type);

    int num = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            bi.createGraphics().drawImage(buffImages[num], width * j, height * i, null);
            num++;
        }
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(bi, "png", os);
    } finally {
        os.close();
    }

    result.setDatawidth(width * cols);
    result.setDataheight(height * rows);
    result.setData(os.toByteArray());
    return result;
}

From source file:ImageDuplicity.java

private void createOffscreenImage() {
    Dimension d = getSize();//from   ww w.j  a v a 2s  . c om
    int width = d.width;
    int height = d.height;
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    try {
        String filename = "largeJava2sLogo.jpg";
        InputStream in = getClass().getResourceAsStream(filename);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
        BufferedImage image = decoder.decodeAsBufferedImage();
        in.close();
        g2.drawImage(image, 0, 0, width, height, null);
    } catch (Exception e) {
        System.out.print(e);
    }

    g2.setStroke(new BasicStroke(2));
    Color[] colors = { Color.red, Color.blue, Color.green };
    for (int i = -32; i < 40; i += 8) {
        g2.setPaint(colors[Math.abs(i) % 3]);
        g2.drawOval(i, i, width - i * 2, height - i * 2);
    }
}

From source file:com.skcraft.launcher.swing.InstanceTableModel.java

private ImageIcon buildDownloadIcon(BufferedImage instanceIcon) {
    try {//from  w  w w. j ava2 s  . co  m
        BufferedImage iconBg = instanceIcon;
        BufferedImage iconFg = ImageIO.read(Launcher.class.getResource("download_icon_overlay.png"));
        BufferedImage iconCombined = new BufferedImage(iconBg.getWidth(), iconBg.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D canvas = iconCombined.createGraphics();
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        canvas.drawImage(iconBg, 0, 0, null);
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        canvas.drawImage(iconFg, iconBg.getWidth() - iconFg.getWidth(), iconBg.getHeight() - iconFg.getHeight(),
                null);
        canvas.dispose();
        return new ImageIcon(iconCombined);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

private BufferedImage toBufferedImage(Image image) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.createGraphics();
    g.setColor(Color.white);/*from  w  ww.  j a va 2s.  c  o  m*/
    g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bufferedImage;
}

From source file:image.writer.ImageWriterExample1.java

/**
 * Creates a bitmap file. We paint a few things on a bitmap and then save the bitmap using
 * an ImageWriter.//from ww w.j  av a2 s. c o m
 * @param outputFile the target file
 * @param format the target format (a MIME type, ex. "image/png")
 * @throws IOException In case of an I/O error
 */
public void generateBitmapUsingJava2D(File outputFile, String format) throws IOException {
    //String compression = "CCITT T.6";
    String compression = "PackBits";
    boolean monochrome = compression.startsWith("CCITT"); //CCITT is for 1bit b/w only

    BufferedImage bimg;
    if (monochrome) {
        bimg = new BufferedImage(400, 200, BufferedImage.TYPE_BYTE_BINARY);
    } else {
        bimg = new BufferedImage(400, 200, BufferedImage.TYPE_INT_RGB);
    }

    Graphics2D g2d = bimg.createGraphics();
    g2d.setBackground(Color.white);
    g2d.clearRect(0, 0, 400, 200);
    g2d.setColor(Color.black);

    //Paint something
    paintSome(g2d, 1);

    OutputStream out = new java.io.FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    try {

        ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(format);
        ImageWriterParams params = new ImageWriterParams();
        params.setCompressionMethod(compression);
        params.setResolution(72);
        writer.writeImage(bimg, out, params);

    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:MainClass.java

public void paint(Graphics g) {
    BufferedImage bim;

    TexturePaint tp;/*from   w  ww.ja  v  a 2  s .  c  o m*/

    String mesg = "www.java2s.com";

    Font myFont = new Font("Lucida Regular", Font.BOLD, 72);

    Color[] colors = { Color.red, Color.blue, Color.yellow, };

    int width = 8, height = 8;
    bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bim.createGraphics();
    for (int i = 0; i < width; i++) {
        g2.setPaint(colors[(i / 2) % colors.length]);
        g2.drawLine(0, i, i, 0);
        g2.drawLine(width - i, height, width, height - i);
    }
    Rectangle r = new Rectangle(0, 0, bim.getWidth(), bim.getHeight());
    tp = new TexturePaint(bim, r);

    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(tp);
    g2d.setFont(myFont);
    g2d.drawString(mesg, 20, 100);
}

From source file:com.tur0kk.facebook.FacebookClient.java

public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
        // facebook requires multipart post structure
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("message", msg); // description

        if (placeId != null && !"".equals(placeId)) {
            builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences
        }//from w w  w . j  av  a2s.c o m

        // convert image to bytearray and append to multipart
        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(image, 0, 0, null);
        bGr.dispose();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bimage, "png", baos);
        builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

        // generate multipart byte stream and add to payload of post package
        HttpEntity multipart = builder.build();
        ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream(
                (int) multipart.getContentLength());
        multipart.writeTo(multipartOutStream);
        request.addPayload(multipartOutStream.toByteArray());

        // set header of post package
        Header contentType = multipart.getContentType();
        request.addHeader(contentType.getName(), contentType.getValue());

        // send and response answer
        Response response = request.send();
        return response.getBody();
    } else {
        throw new RuntimeException("message and image needed");
    }
}

From source file:ddf.catalog.transformer.input.pptx.PptxInputTransformer.java

/**
 * If the slide show doesn't contain any slides, then return null. Otherwise, return jpeg
 * image data of the first slide in the deck.
 *
 * @param slideShow/*ww w. j  a v  a 2  s .  c om*/
 * @return jpeg thumbnail or null if thumbnail can't be created
 * @throws IOException
 */
private byte[] generatePptxThumbnail(XMLSlideShow slideShow) throws IOException {

    if (slideShow.getSlides().isEmpty()) {
        LOGGER.info("the powerpoint file does not contain any slides, skipping thumbnail generation");
        return null;
    }

    Dimension pgsize = slideShow.getPageSize();

    int largestDimension = (int) Math.max(pgsize.getHeight(), pgsize.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (pgsize.getHeight() * scalingFactor);
    int scaledWidth = (int) (pgsize.getWidth() * scalingFactor);
    BufferedImage img = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D graphics = img.createGraphics();

    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        graphics.scale(scalingFactor, scalingFactor);

        slideShow.getSlides().get(0).draw(graphics);

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIOUtil.writeImage(img, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
            return outputStream.toByteArray();
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof javax.imageio.IIOException) {
            LOGGER.warn("unable to generate thumbnail for PPTX file", e);
        } else {
            throw e;
        }
    } finally {
        graphics.dispose();
    }

    return null;
}

From source file:Main.java

public void paint(Graphics g) {
    BufferedImage bim;

    TexturePaint tp;//from ww w  .  j  a v a2 s .  com

    String mesg = "www.java2s.com";

    Font myFont = new Font("Lucida Regular", Font.BOLD, 72);

    Color[] colors = { Color.red, Color.blue, Color.yellow, };

    int width = 8, height = 8;
    bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bim.createGraphics();
    for (int i = 0; i < width; i++) {
        g2.setPaint(colors[(i / 2) % colors.length]);
        g2.drawLine(0, i, i, 0);
        g2.drawLine(width - i, height, width, height - i);
    }
    Rectangle r = new Rectangle(0, 0, bim.getWidth(), bim.getHeight());
    tp = new TexturePaint(bim, r);
    System.out.println(tp.getAnchorRect());

    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(tp);
    g2d.setFont(myFont);
    g2d.drawString(mesg, 20, 100);
}

From source file:Main.java

public void paint(Graphics g) {
    BufferedImage bim;

    TexturePaint tp;/*ww w. j  av  a  2 s .  c om*/

    String mesg = "www.java2s.com";

    Font myFont = new Font("Lucida Regular", Font.BOLD, 72);

    Color[] colors = { Color.red, Color.blue, Color.yellow, };

    int width = 8, height = 8;
    bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bim.createGraphics();
    for (int i = 0; i < width; i++) {
        g2.setPaint(colors[(i / 2) % colors.length]);
        g2.drawLine(0, i, i, 0);
        g2.drawLine(width - i, height, width, height - i);
    }
    Rectangle r = new Rectangle(0, 0, bim.getWidth(), bim.getHeight());
    tp = new TexturePaint(bim, r);
    System.out.println(tp.getImage());

    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(tp);
    g2d.setFont(myFont);
    g2d.drawString(mesg, 20, 100);
}