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:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*ww w .  j  a v  a 2s  .com*/
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeBMP(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;

    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {

        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("bmp").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*w  w  w . j a va2 s.  c  o  m*/
 * @param destFile
 * @param quality
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeJpeg(Image img, String destFile, float quality, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.

    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:com.shending.support.CompressPic.java

/**
 * ?/*w  w  w  .  j ava 2 s  .  c  o  m*/
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static Image estampar(Image im) {
    try {//from ww w.jav  a 2  s .c  o m
        Image temp = new ImageIcon(im).getImage();

        BufferedImage buf = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) buf.getGraphics();

        g2.drawImage(temp, 0, 0, null);
        g2.setBackground(Color.BLUE);

        Dimension dimensaoFoto = new Dimension(im.getWidth(null), im.getHeight(null));

        // aplicar texto
        if (texto != null) {
            Util.out.println("aplicando texto " + texto);

            Font fonte = new Font(txFamilia, txEstilo, txTamanho);
            g2.setFont(fonte);
            FontMetrics fm = g2.getFontMetrics(fonte);
            Dimension dimensaoTexto = new Dimension(fm.stringWidth(texto), fm.getHeight());
            Point posTexto = calculaPosicao(dimensaoFoto, dimensaoTexto, txMargem, txPosicao);

            g2.setPaint(txCorFundo);
            g2.drawString(texto, (int) posTexto.getX() + 1, (int) posTexto.getY() + 1 + fm.getHeight());
            g2.setPaint(txCorFrente);
            g2.drawString(texto, (int) posTexto.getX(), (int) posTexto.getY() + fm.getHeight());
        }

        // aplicar marca dagua
        if (marcadagua != null) {
            Image marca = new ImageIcon(marcadagua).getImage();
            int rule = AlphaComposite.SRC_OVER;
            float alpha = (float) mdTransparencia / 100;
            Point pos = calculaPosicao(dimensaoFoto, new Dimension(marca.getWidth(null), marca.getHeight(null)),
                    mdMargem, mdPosicao);

            g2.setComposite(AlphaComposite.getInstance(rule, alpha));
            g2.drawImage(marca, (int) pos.getX(), (int) pos.getY(), null);
        }

        g2.dispose();
        //return (Image) buf;
        return Toolkit.getDefaultToolkit().createImage(buf.getSource());
    } catch (Exception e) {
        Util.err.println("[Thumbnail.estampar]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
        return im;
    }
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static BufferedImage toByteImage(BufferedImage image) {
    BufferedImage newImage = createByteImage(image.getWidth(), image.getHeight());
    Graphics2D graphics = newImage.createGraphics();
    graphics.setBackground(Color.white);
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.drawImage(image, 0, 0, null);
    return newImage;
}

From source file:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Combines JPG images. Combining JPG images is different from the other image types since JPG
 * has to use an other imageType: BufferedImage.TYPE_INT_RGB.
 *
 * @param images BufferedImage array with the images tha have to be combined.
 *
 * @return BufferedImage/*from  w w  w . j  av a 2s. co m*/
 */
// <editor-fold defaultstate="" desc="combineJPGImages(BufferedImage [] images) method.">
private static BufferedImage combineJPGImages(BufferedImage[] images) {
    int width = images[0].getWidth();
    int height = images[0].getHeight();

    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gbi = newBufIm.createGraphics();
    gbi.drawImage(images[0], 0, 0, null);

    for (int i = 1; i < images.length; i++) {
        gbi.drawImage(images[i], 0, 0, null);
    }
    return newBufIm;
}

From source file:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Combines GIF, TIFF or PNG images. Combining these images is different from the JPG image types since these
 * has to use an other imageType: BufferedImage.TYPE_INT_ARGB_PRE.
 *
 * @param images BufferedImage array with the images tha have to be combined.
 *
 * @return BufferedImage/*ww  w . ja  v  a 2s  . co m*/
 */
// <editor-fold defaultstate="" desc="combineOtherImages(BufferedImage [] images) method.">
private static BufferedImage combineOtherImages(BufferedImage[] images) {
    int width = images[0].getWidth();
    int height = images[0].getHeight();

    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D gbi = newBufIm.createGraphics();

    gbi.drawImage(images[0], 0, 0, null);
    gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_OVER, 1.0f));

    for (int i = 1; i < images.length; i++) {
        gbi.drawImage(images[i], 0, 0, null);
    }
    return newBufIm;
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) and save it to file
  * @param image input image for scaling
  * @param scale_factor factor for scaling image
 * @param rez writes resulting image to a file
 * @throws IOException/*from  www  .  ja  v  a2s . c  o m*/
  */
public static void saveScaledImageWidth(BufferedImage image, double scale_factor, OutputStream rez)
        throws IOException {
    //long time_resize = System.currentTimeMillis();
    if (scale_factor == 1) {
        writeImage(image, 1, rez);
    } else {
        int width = (int) (scale_factor * image.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //BufferedImage scaled_bi = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() );
        int type = image.getType();
        BufferedImage scaled_bi;
        if (type == BufferedImage.TYPE_CUSTOM) {
            scaled_bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        } else {
            scaled_bi = new BufferedImage(width, height, type);
        }

        Graphics2D g2 = scaled_bi.createGraphics();

        //g2.drawImage(image, at, null);
        g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        writeImage(scaled_bi, 1, rez);

        g2.dispose();
    }
    //time_resize = System.currentTimeMillis() - time_resize;
    //System.out.print("time_resize=" + (time_resize) + "; ");
}

From source file:Main.java

public static void draw(BufferedImage imageBG, BufferedImage imageFG) {
    Ellipse2D.Double ellipse1 = new Ellipse2D.Double(20, 20, 30, 30);
    Ellipse2D.Double ellipse2 = new Ellipse2D.Double(25, 25, 30, 30);
    Area circle = new Area(ellipse1);
    circle.subtract(new Area(ellipse2));

    Graphics2D g = imageBG.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.setClip(circle);/* w  w w .ja v a  2s .  c o m*/
    g.drawImage(imageFG, 0, 0, null);
    g.setClip(null);
    Stroke s = new BasicStroke(2);
    g.setStroke(s);
    g.setColor(Color.BLACK);
    g.draw(circle);
    g.dispose();

    JLabel l = new JLabel(new ImageIcon(imageBG));
    JOptionPane.showMessageDialog(null, l);
}

From source file:com.alvermont.terraj.stargen.ui.UIUtils.java

/**
 * Scale an image to a particular X and Y size in pixels
 * /*from ww  w .  j  av a2 s  .co  m*/
 * @param image The image to be scaled
 * @param pixelsX The desired horizontal size in pixels
 * @param pixelsY The desired vertical size in pixels
 * @return A new image scaled to the requested dimensions
 */
public static BufferedImage scaleImage(BufferedImage image, int pixelsX, int pixelsY) {
    int actualWidth = image.getWidth();
    int actualHeight = image.getHeight();

    // work out the scale factor

    double sx = (float) (pixelsX) / actualWidth;
    double sy = (float) (pixelsY) / actualHeight;

    BufferedImage nbi = new BufferedImage(pixelsX, pixelsY, image.getType());

    Graphics2D g2 = nbi.createGraphics();
    AffineTransform at = AffineTransform.getScaleInstance(sx, sy);

    g2.setTransform(at);

    g2.drawImage(image, 0, 0, null);

    return nbi;
}