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.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*from   w w  w  .  j  a  va 2  s .  c om*/
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    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();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), 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((float) (DEST_QUALITY / 100.0));
            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 {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.sketchy.image.ImageProcessingThread.java

public static BufferedImage flipImage(BufferedImage image, FlipOption flipOption) {

    if (flipOption == FlipOption.FLIP_NONE)
        return image;

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    BufferedImage flippedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = flippedImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

    int startX = 0;
    int startY = 0;
    int endX = imageWidth;
    int endY = imageHeight;
    if ((flipOption == FlipOption.FLIP_HORIZONTAL) || (flipOption == FlipOption.FLIP_BOTH)) {
        startX = imageWidth;//from  w w  w  .  j  a va 2s .c  o m
        endX = -imageWidth;
    }
    if ((flipOption == FlipOption.FLIP_VERTICAL) || (flipOption == FlipOption.FLIP_BOTH)) {
        startY = imageHeight;
        endY = -imageHeight;
    }

    g.drawImage(image, startX, startY, endX, endY, null);
    g.dispose();
    return flippedImage;
}

From source file:com.taunova.app.libview.components.ImageHelpers.java

public static Image getScaledImage(BufferedImage image, int width) {
    Dimension d = getScaledDimension(image, width);
    Image scaledImage = image.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH);

    BufferedImage resizedImage = null;

    final boolean OPTIMIZE_SCALE = true;

    if (OPTIMIZE_SCALE) {
        ResampleOp resampleOp = new ResampleOp(100, 200);
        resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
        resizedImage = resampleOp.filter(image, null);
    } else {// w ww. jav a  2s  .c  o m
        resizedImage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(scaledImage, 0, 0, d.width, d.height, null);
        g.dispose();
    }

    return resizedImage;
}

From source file:com.t3.image.ImageUtil.java

/**
 * Create a copy of the image that is compatible with the current graphics context
 * and scaled to the supplied size//  w  w  w .  j a  va2s.com
 */
public static BufferedImage createCompatibleImage(Image img, int width, int height, Map<String, Object> hints) {

    width = Math.max(width, 1);
    height = Math.max(height, 1);

    int transparency;
    if (hints != null && hints.containsKey(HINT_TRANSPARENCY)) {
        transparency = (Integer) hints.get(HINT_TRANSPARENCY);
    } else {
        transparency = pickBestTransparency(img);
    }
    BufferedImage compImg = new BufferedImage(width, height, transparency);

    Graphics2D g = null;
    try {
        g = compImg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        g.drawImage(img, 0, 0, width, height, null);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }

    return compImg;
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);/*from   w ww  . j  a  v a 2  s .c  om*/
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists()) {
        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;

            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 {
        IMOperation operation = new IMOperation();
        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:net.sf.webphotos.tools.Thumbnail.java

private static boolean save(Image thumbnail, String nmArquivo) {
    try {/*from   w w  w.  ja v a2s  . co m*/
        // This code ensures that all the
        // pixels in the image are loaded.
        Image temp = new ImageIcon(thumbnail).getImage();

        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics();

        // Clear background and paint the image.
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();

        // write the jpeg to a file
        File file = new File(nmArquivo);
        // Recria o arquivo se existir
        if (file.exists()) {
            Util.out.println("Redefinindo a Imagem: " + nmArquivo);
            file.delete();
            file = new File(nmArquivo);
        }

        // encodes image as a JPEG file
        ImageIO.write(bufferedImage, IMAGE_FORMAT, file);

        return true;
    } catch (IOException ioex) {
        ioex.printStackTrace(Util.err);
        return false;
    }
}

From source file:business.model.CaptchaModel.java

/**
 *
 * @param CaptchaText/*from  w w w  .  j  a va 2 s  .com*/
 * @return
 */
public static BufferedImage CreateCaptchaImageOld(String CaptchaText) {
    BufferedImage localBufferedImage = new BufferedImage(width, height, 1);
    try {
        Graphics2D localGraphics2D = localBufferedImage.createGraphics();
        //        List<Font> fonts = FontFactory.getListFont();
        List<Font> fonts = new ArrayList<Font>();
        if (fonts.isEmpty()) {
            fonts.add(new Font("Nimbus Roman No9 L", 1, 30));
            fonts.add(new Font("VN-NTime", 1, 30));
            fonts.add(new Font("DT-Times", 1, 30));
            fonts.add(new Font("Times New Roman", 1, 30));
            fonts.add(new Font("Vni-Book123", 1, 30));
            fonts.add(new Font("VNI-Centur", 1, 30));
            fonts.add(new Font("DT-Brookly", 1, 30));
        }
        //        fonts.add(loadFont("BINHLBI.TTF"));
        RenderingHints localRenderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        localRenderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        localGraphics2D.setRenderingHints(localRenderingHints);
        localGraphics2D.fillRect(0, 0, width, height);
        localGraphics2D.setColor(new Color(50, 50, 50));
        Random localRandom = new Random();
        int i = 0;
        int j = 0;
        for (int k = 0; k < CaptchaText.length(); k++) {
            i += 25 + Math.abs(localRandom.nextInt()) % 5;
            j = 25 + Math.abs(localRandom.nextInt()) % 20;
            int tmp = localRandom.nextInt(fonts.size() - 1);
            localGraphics2D.setFont(fonts.get(tmp));

            localGraphics2D.drawChars(CaptchaText.toCharArray(), k, 1, i, j);
        }
        localBufferedImage = getDistortedImage(localBufferedImage);
        Graphics2D localGraphics2D2 = localBufferedImage.createGraphics();
        localGraphics2D2.setRenderingHints(localRenderingHints);
        //        localGraphics2D2.fillRect(0, 0, width, height);
        localGraphics2D2.setColor(new Color(50, 50, 50));
        CubicCurve2D c = new CubicCurve2D.Double();// draw QuadCurve2D.Float with set coordinates
        for (int l = 0; l < 7; l++) {
            int x1 = Util.rand(0, width / 2);
            ;
            int x2 = Util.rand(width / 2, width);
            int y1 = Util.rand(0, height);
            int y2 = Util.rand(0, height);
            int ctrlx1 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly1 = y1;
            int ctrlx2 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly2 = y2;

            c.setCurve(x1, y1, ctrlx2, ctrly2, ctrlx1, ctrly1, x2, y2);
            localGraphics2D2.draw(c);
            //            localGraphics2D2.drawLine(randomX1(), randomY1(), randomX2(), randomY2());
        }

        localGraphics2D.dispose();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
    return localBufferedImage;
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static BufferedImage trim9PBorder(BufferedImage inputImage) {
    BufferedImage trimedImage = UIUtil.createImage(inputImage.getWidth() - 2, inputImage.getHeight() - 2,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = trimedImage.createGraphics();
    g.drawImage(inputImage, 0, 0, trimedImage.getWidth(), trimedImage.getHeight(), 1, 1,
            inputImage.getWidth() - 1, inputImage.getHeight() - 1, null);
    g.dispose();//from ww  w.  ja  v  a 2  s .c  o m
    return trimedImage;
}

From source file:at.gv.egiz.pdfas.common.utils.ImageUtils.java

public static BufferedImage convertRGBAToIndexed(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    Graphics g = dest.getGraphics();
    g.setColor(new Color(231, 20, 189));
    g.fillRect(0, 0, dest.getWidth(), dest.getHeight()); // fill with a
    // hideous color
    // and make it
    // transparent
    dest = makeTransparent(dest, 0, 0);/*from  ww w. j  ava 2 s  .  c om*/
    dest.createGraphics().drawImage(src, 0, 0, null);
    return dest;
}

From source file:com.sketchy.image.ImageProcessingThread.java

public static BufferedImage resizeImage(BufferedImage image, int drawingWidth, int drawingHeight,
        CenterOption centerOption, ScaleOption scaleOption) {

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    double widthScale = drawingWidth / (double) imageWidth;
    double heightScale = drawingHeight / (double) imageHeight;
    double scale = Math.min(widthScale, heightScale);

    int scaleWidth = (int) (imageWidth * scale);
    int scaleHeight = (int) (imageHeight * scale);

    BufferedImage resizedImage = new BufferedImage(scaleWidth, scaleHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = resizedImage.createGraphics();

    if (scaleOption == ScaleOption.SCALE_AREA_AVERAGING) {
        ImageProducer prod = new FilteredImageSource(image.getSource(),
                new AreaAveragingScaleFilter(scaleWidth, scaleHeight));
        Image img = Toolkit.getDefaultToolkit().createImage(prod);
        g.drawImage(img, 0, 0, scaleWidth, scaleHeight, null); // it's already scaled
    } else {/*  w w  w  . ja  v a 2 s  .  c  om*/
        if (scaleOption == ScaleOption.SCALE_NEAREST_NEIGHBOR) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        } else if (scaleOption == ScaleOption.SCALE_BICUBIC) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        } else if (scaleOption == ScaleOption.SCALE_BILINEAR) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
        g.drawImage(image, 0, 0, scaleWidth, scaleHeight, 0, 0, imageWidth, imageHeight, null);
    }
    g.dispose();

    int cropWidth = (int) Math.min(scaleWidth, drawingWidth);
    int cropHeight = (int) Math.min(scaleHeight, drawingHeight);

    int drawingLeft = 0;
    int drawingTop = 0;
    if ((centerOption == CenterOption.CENTER_HORIZONTAL) || (centerOption == CenterOption.CENTER_BOTH)) {
        drawingLeft = (int) ((drawingWidth - cropWidth) / 2.0);
    }
    if ((centerOption == CenterOption.CENTER_VERTICAL) || (centerOption == CenterOption.CENTER_BOTH)) {
        drawingTop = (int) ((drawingHeight - cropHeight) / 2.0);
    }

    BufferedImage croppedImage = resizedImage.getSubimage(0, 0, cropWidth, cropHeight);
    resizedImage = null;

    BufferedImage drawingImage = new BufferedImage(drawingWidth, drawingHeight, BufferedImage.TYPE_INT_ARGB);
    g = drawingImage.createGraphics();
    g.drawImage(croppedImage, drawingLeft, drawingTop, drawingLeft + cropWidth, drawingTop + cropHeight, 0, 0,
            cropWidth, cropHeight, null);
    g.dispose();

    croppedImage = null;
    return drawingImage;
}