Example usage for java.awt Graphics2D drawImage

List of usage examples for java.awt Graphics2D drawImage

Introduction

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

Prototype

public abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

Source Link

Document

Renders a BufferedImage that is filtered with a BufferedImageOp .

Usage

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Masks out white colour// w  ww .  j  a v  a 2 s  .  c om
 * @param image the image to mask out
 * @return the resulting image
 */
private BufferedImage transformWhiteToTransparent(BufferedImage image) {

    BufferedImage dest = image;
    if (image.getType() != BufferedImage.TYPE_INT_ARGB) {
        dest = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();

        image.flush();
    }

    // Mask out the white pixels
    final int width = image.getWidth();
    int[] imgData = new int[width];

    for (int y = 0; y < dest.getHeight(); y++) {
        // fetch a line of data from each image
        dest.getRGB(0, y, width, 1, imgData, 0, 1);
        // apply the mask
        for (int x = 0; x < width; x++) {
            for (Color col : MASKED_COLORS) {
                int colDist = Math.abs(col.getRed() - (imgData[x] >> 16 & 0x000000FF))
                        + Math.abs(col.getGreen() - (imgData[x] >> 8 & 0x000000FF))
                        + Math.abs(col.getBlue() - (imgData[x] & 0x000000FF));
                if (colDist <= COLOR_DIST) {
                    imgData[x] = 0x00FFFFFF & imgData[x];
                }
            }
        }
        // replace the data
        dest.setRGB(0, y, width, 1, imgData, 0, 1);
    }
    return dest;
}

From source file:net.groupbuy.util.ImageUtils.java

/**
 * ?/*  w  w w .j  av  a  2 s . c om*/
 * 
 * @param srcFile
 *            ?
 * @param destFile
 *            
 * @param watermarkFile
 *            ?
 * @param watermarkPosition
 *            ??
 * @param alpha
 *            ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            FileUtils.copyFile(srcFile, destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(watermarkFile.getPath());
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * ???//  w w  w. j a  va 2s . co m
 * 
 * @param imgfile
 * @param width
 * @param height
 * @return
 */
public static BufferedImage shrinkAndTrimImage(BufferedImage imgfile, int width, int height) {
    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();
    double ratio = Math.max((double) width / (double) iwidth, (double) height / (double) iheight);

    int shrinkedWidth;
    int shrinkedHeight;

    if ((iwidth <= width) || (iheight < height)) {
        shrinkedWidth = iwidth;
        shrinkedHeight = iheight;
    } else {
        shrinkedWidth = (int) (iwidth * ratio);
        shrinkedHeight = (int) (iheight * ratio);
    }

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);

    int w_size = targetImage.getWidth(null);
    int h_size = targetImage.getHeight(null);
    if (targetImage.getWidth(null) < width) {
        w_size = width;
    }
    if (targetImage.getHeight(null) < height) {
        h_size = height;
    }
    BufferedImage tmpImage = new BufferedImage(w_size, h_size, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = tmpImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.setColor(Color.WHITE);
    // ??????????????
    g.fillRect(0, 0, w_size, h_size);
    int diff_w = 0;
    int diff_h = 0;
    if (width > shrinkedWidth) {
        diff_w = (width - shrinkedWidth) / 2;
    }
    if (height > shrinkedHeight) {
        diff_h = (height - shrinkedHeight) / 2;
    }
    g.drawImage(targetImage, diff_w, diff_h, null);

    int _iwidth = tmpImage.getWidth();
    int _iheight = tmpImage.getHeight();
    BufferedImage _tmpImage;
    if (_iwidth > _iheight) {
        int diff = _iwidth - width;
        _tmpImage = tmpImage.getSubimage(diff / 2, 0, width, height);
    } else {
        int diff = _iheight - height;
        _tmpImage = tmpImage.getSubimage(0, diff / 2, width, height);
    }
    return _tmpImage;
}

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * ?/*from w ww . ja  v  a  2  s . c  om*/
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

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

/**
 * Get the bytes of the final image.//from   ww w .j  a v  a 2  s.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.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
        }//  w ww.j  a  va2  s .com

        // 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:edu.clemson.cs.nestbed.client.gui.MotePanel.java

public void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

    Graphics2D g = (Graphics2D) graphics;

    g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
    g.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());

    g.drawImage(icon, getWidth() / 4, getHeight() / 4, null);
}

From source file:hudson.jbpm.PluginImpl.java

/**
 * Draws a JPEG for a process definition
 * /*from www.  j  a v  a  2  s  .c o  m*/
 * @param req
 * @param rsp
 * @param processDefinition
 * @throws IOException
 */
public void doProcessDefinitionImage(StaplerRequest req, StaplerResponse rsp,
        @QueryParameter("processDefinition") long processDefinition) throws IOException {

    JbpmContext context = getCurrentJbpmContext();
    ProcessDefinition definition = context.getGraphSession().getProcessDefinition(processDefinition);
    FileDefinition fd = definition.getFileDefinition();
    byte[] bytes = fd.getBytes("processimage.jpg");
    rsp.setContentType("image/jpeg");
    ServletOutputStream output = rsp.getOutputStream();

    BufferedImage loaded = ImageIO.read(new ByteArrayInputStream(bytes));
    BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = aimg.createGraphics();
    g.drawImage(loaded, null, 0, 0);
    g.dispose();
    ImageIO.write(aimg, "jpg", output);
    output.flush();
    output.close();
}

From source file:Main.java

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(getBackground());//from w w  w  . j  av a  2  s  . c o  m
    g2d.fillRect(0, 0, getWidth(), getHeight());
    if (image != null) {
        int x = getWidth() - image.getWidth();
        int y = getHeight() - image.getHeight();
        g2d.drawImage(image, x, y, this);
    }
    super.paintComponent(g2d);
    g2d.dispose();
}

From source file:doge.photo.DogePhotoManipulator.java

private void renderOverlay(BufferedImage image, Graphics2D graphics) {
    getRandomText().render(image, graphics);
    int y = image.getHeight() - this.dogeLogo.getHeight();
    graphics.drawImage(this.dogeLogo, 0, y, null);
}