Java Tutorial/2D Graphics/BufferedImage

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

A buffered image is a type of image whose pixels can be modified.

   <source lang="java">

import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   int width = 100;
   int height = 100;
   BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
 }

}</source>





BufferedImage.TYPE_INT_RGB

   <source lang="java">

import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class BufferedImageTYPE_INT_RGB extends JFrame {

 public BufferedImageTYPE_INT_RGB() {
   getContentPane().add(new DrawingCanvas());
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setSize(500, 500);
   setVisible(true);
 }
 public static void main(String arg[]) {
   new BufferedImageTYPE_INT_RGB();
 }

} class DrawingCanvas extends JPanel {

 Font font = new Font("Dialog", Font.BOLD, 40);
 FontMetrics fontMetrics;
 DrawingCanvas() {
   setSize(300, 300);
   setBackground(Color.white);
   fontMetrics = getFontMetrics(font);
 }
 public void paint(Graphics g) {
   Graphics2D g2D = (Graphics2D) g;
   int w = getSize().width;
   int h = getSize().height;
   BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
   Graphics2D big = bi.createGraphics();
   big.setColor(Color.magenta);
   big.fillRect(0, 0, 5, 5);
   big.setColor(Color.black);
   big.fillOval(0, 0, 5, 5);
   Rectangle r = new Rectangle(0, 0, 5, 5);
   TexturePaint tp = new TexturePaint(bi, r);
   g2D.setPaint(tp);
   g2D.drawString("Graphics", 30, 100);
 }

}</source>





Converting a Buffered Image (BufferedImage) from an Image

   <source lang="java">

import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_3BYTE_BGR);
   Image img = Toolkit.getDefaultToolkit().createImage(
       bufferedImage.getSource());
 }

}</source>





Converting a Colored Buffered Image to Gray

   <source lang="java">

import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; public class Main {

 public static void main(String[] argv) throws Exception {
   ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
   ColorConvertOp op = new ColorConvertOp(cs, null);
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Create a buffered image that supports transparency

   <source lang="java">

import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   int width = 100;
   int height = 100;
   BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
 }

}</source>





Create an image that does not support transparency

   <source lang="java">

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Transparency; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class BasicShapes extends JPanel {

 public void paint(Graphics g) {
   Graphics2D g2d = (Graphics2D) g;
   int width = 100;
   int height = 100;
   BufferedImage bimage = g2d.getDeviceConfiguration().createCompatibleImage(
       width, height, Transparency.OPAQUE);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Basic Shapes");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new BasicShapes());
   frame.setSize(350, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }

}</source>





Create an image that supports arbitrary levels of transparency

   <source lang="java">

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Transparency; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class BasicShapes extends JPanel {

 public void paint(Graphics g) {
   Graphics2D g2d = (Graphics2D) g;
   int width = 100;
   int height = 100;
   BufferedImage bimage = g2d.getDeviceConfiguration().createCompatibleImage(
       width, height, Transparency.TRANSLUCENT);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Basic Shapes");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new BasicShapes());
   frame.setSize(350, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }

}</source>





Create an image that supports transparent pixels

   <source lang="java">

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Transparency; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class BasicShapes extends JPanel {

 public void paint(Graphics g) {
   Graphics2D g2d = (Graphics2D) g;
   int width = 100;
   int height = 100;
   BufferedImage bimage = g2d.getDeviceConfiguration().createCompatibleImage(
       width, height, Transparency.BITMASK);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Basic Shapes");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new BasicShapes());
   frame.setSize(350, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }

}</source>





Create buffered image that does not support transparency

   <source lang="java">

import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   int width = 100;
   int height = 100;
   
   BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 
 }

}</source>





Create BufferredImage with colors based on integer array

   <source lang="java">

import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.JFrame; public class ColorPan extends JComponent {

 public void paint(Graphics g) {
   int width = getSize().width;
   int height = getSize().height;
   int[] data = new int[width * height];
   int i = 0;
   for (int y = 0; y < height; y++) {
     int red = (y * 255) / (height - 1);
     for (int x = 0; x < width; x++) {
       int green = (x * 255) / (width - 1);
       int blue = 128;
       data[i++] = (red << 16) | (green << 8) | blue;
     }
   }
   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   image.setRGB(0, 0, width, height, data, 0, width);
   g.drawImage(image, 0, 0, this);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("ColorPan");
   frame.getContentPane().add(new ColorPan());
   frame.setSize(300, 300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
 }

}</source>





Create Gradient Image

   <source lang="java">

/*

* Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.image.BufferedImage; /**

* 
* @author aim
*/

public class Utils {

 public static BufferedImage createGradientImage(int width, int height, Color gradient1,
     Color gradient2) {
   BufferedImage gradientImage = createCompatibleImage(width, height);
   GradientPaint gradient = new GradientPaint(0, 0, gradient1, 0, height, gradient2, false);
   Graphics2D g2 = (Graphics2D) gradientImage.getGraphics();
   g2.setPaint(gradient);
   g2.fillRect(0, 0, width, height);
   g2.dispose();
   return gradientImage;
 }
 private static BufferedImage createCompatibleImage(int width, int height) {
   return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
       .getDefaultConfiguration().createCompatibleImage(width, height);
 }

}</source>





Create Gradient Mask

   <source lang="java">

/*

* Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import javax.swing.SwingConstants; /**

* 
* @author aim
*/

public class Utils {

 public static BufferedImage createGradientMask(int width, int height, int orientation) {
   // algorithm derived from Romain Guy"s blog
   BufferedImage gradient = new BufferedImage(width, height,
           BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = gradient.createGraphics();
   GradientPaint paint = new GradientPaint(0.0f, 0.0f,
           new Color(1.0f, 1.0f, 1.0f, 1.0f),
           orientation == SwingConstants.HORIZONTAL? width : 0.0f, 
           orientation == SwingConstants.VERTICAL? height : 0.0f,
           new Color(1.0f, 1.0f, 1.0f, 0.0f));
   g.setPaint(paint);
   g.fill(new Rectangle2D.Double(0, 0, width, height));
   g.dispose();
   gradient.flush();
   return gradient;

} }</source>





Create Headless BufferedImage

   <source lang="java">

/*

* Copyright (c) JForum Team
* All rights reserved.
* Redistribution and use in source and binary forms, 
* with or without modification, are permitted provided 
* that the following conditions are met:
* 1) Redistributions of source code must retain the above 
* copyright notice, this list of conditions and the 
* following  disclaimer.
* 2)  Redistributions in binary form must reproduce the 
* above copyright notice, this list of conditions and 
* the following disclaimer in the documentation and/or 
* other materials provided with the distribution.
* 3) Neither the name of "Rafael Steil" nor 
* the names of its contributors may be used to endorse 
* or promote products derived from this software without 
* specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
* IN CONTRACT, STRICT LIABILITY, OR TORT 
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
* 
* This file creation date: 21/04/2004 - 19:54:16
* The JForum Project
* http://www.jforum.net
*/

import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.PixelGrabber; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Locale; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream;

/**

* Utilities methods for image manipulation. It does not support writting of GIF images, but it can
* read from. GIF images will be saved as PNG.
* 
* @author Rafael Steil
* @version $Id: ImageUtils.java,v 1.23 2007/09/09 01:05:22 rafaelsteil Exp $
*/

public class ImageUtils {

 public static final int IMAGE_UNKNOWN = -1;
 public static final int IMAGE_JPEG = 0;
 public static final int IMAGE_PNG = 1;
 public static final int IMAGE_GIF = 2;
 /**
  * Resizes an image
  * 
  * @param imgName The image name to resize. Must be the complet path to the file
  * @param type int
  * @param maxWidth The image"s max width
  * @param maxHeight The image"s max height
  * @return A resized BufferedImage
  */
 public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight)
 {
   try {
     return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Resizes an image.
  * 
  * @param image
  *            The image to resize
  * @param maxWidth
  *            The image"s max width
  * @param maxHeight
  *            The image"s max height
  * @return A resized BufferedImage
  * @param type
  *            int
  */
 public static BufferedImage resizeImage(BufferedImage image, int type, int maxWidth, int maxHeight)
 {
   Dimension largestDimension = new Dimension(maxWidth, maxHeight);
   // Original size
   int imageWidth = image.getWidth(null);
   int imageHeight = image.getHeight(null);
   float aspectRatio = (float) imageWidth / imageHeight;
   if (imageWidth > maxWidth || imageHeight > maxHeight) {
     if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
       largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio);
     }
     else {
       largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio);
     }
     imageWidth = largestDimension.width;
     imageHeight = largestDimension.height;
   }
   return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight);
 }
 /**
  * Saves an image to the disk.
  * 
  * @param image  The image to save
  * @param toFileName The filename to use
  * @param type The image type. Use ImageUtils.IMAGE_JPEG to save as JPEG images,
  *  or ImageUtils.IMAGE_PNG to save as PNG.
  * @return false if no appropriate writer is found
  */
 public static boolean saveImage(BufferedImage image, String toFileName, int type)
 {
   try {
     return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Compress and save an image to the disk. Currently this method only supports JPEG images.
  * 
  * @param image The image to save
  * @param toFileName The filename to use
  * @param type The image type. Use ImageUtils.IMAGE_JPEG to save as JPEG images,
  * or ImageUtils.IMAGE_PNG to save as PNG.
  */
 public static void saveCompressedImage(BufferedImage image, String toFileName, int type)
 {
   try {
     if (type == IMAGE_PNG) {
       throw new UnsupportedOperationException("PNG compression not implemented");
     }
     Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
     ImageWriter writer;
     writer = (ImageWriter) iter.next();
     ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
     writer.setOutput(ios);
     ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
     iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     iwparam.setCompressionQuality(0.7F);
     writer.write(null, new IIOImage(image, null, null), iwparam);
     ios.flush();
     writer.dispose();
     ios.close();
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Creates a BufferedImage from an Image. This method can
  * function on a completely headless system. This especially includes Linux and Unix systems
  * that do not have the X11 libraries installed, which are required for the AWT subsystem to
  * operate. This method uses nearest neighbor approximation, so it"s quite fast. Unfortunately,
  * the result is nowhere near as nice looking as the createHeadlessSmoothBufferedImage method.
  * 
  * @param image  The image to convert
  * @param w The desired image width
  * @param h The desired image height
  * @return The converted image
  * @param type int
  */
 public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width, int height)
 {
   if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
     type = BufferedImage.TYPE_INT_ARGB;
   }
   else {
     type = BufferedImage.TYPE_INT_RGB;
   }
   BufferedImage bi = new BufferedImage(width, height, type);
   for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
       bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
     }
   }
   return bi;
 }
 /**
  * Creates a BufferedImage from an Image. This method can
  * function on a completely headless system. This especially includes Linux and Unix systems
  * that do not have the X11 libraries installed, which are required for the AWT subsystem to
  * operate. The resulting image will be smoothly scaled using bilinear filtering.
  * 
  * @param source The image to convert
  * @param w The desired image width
  * @param h The desired image height
  * @return The converted image
  * @param type  int
  */
 public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type, int width, int height)
 {
   if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
     type = BufferedImage.TYPE_INT_ARGB;
   }
   else {
     type = BufferedImage.TYPE_INT_RGB;
   }
   BufferedImage dest = new BufferedImage(width, height, type);
   int sourcex;
   int sourcey;
   double scalex = (double) width / source.getWidth();
   double scaley = (double) height / source.getHeight();
   int x1;
   int y1;
   double xdiff;
   double ydiff;
   int rgb;
   int rgb1;
   int rgb2;
   for (int y = 0; y < height; y++) {
     sourcey = y * source.getHeight() / dest.getHeight();
     ydiff = scale(y, scaley) - sourcey;
     for (int x = 0; x < width; x++) {
       sourcex = x * source.getWidth() / dest.getWidth();
       xdiff = scale(x, scalex) - sourcex;
       x1 = Math.min(source.getWidth() - 1, sourcex + 1);
       y1 = Math.min(source.getHeight() - 1, sourcey + 1);
       rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey), xdiff);
       rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);
       rgb = getRGBInterpolation(rgb1, rgb2, ydiff);
       dest.setRGB(x, y, rgb);
     }
   }
   return dest;
 }
 private static double scale(int point, double scale)
 {
   return point / scale;
 }
 private static int getRGBInterpolation(int value1, int value2, double distance)
 {
   int alpha1 = (value1 & 0xFF000000) >>> 24;
   int red1 = (value1 & 0x00FF0000) >> 16;
   int green1 = (value1 & 0x0000FF00) >> 8;
   int blue1 = (value1 & 0x000000FF);
   int alpha2 = (value2 & 0xFF000000) >>> 24;
   int red2 = (value2 & 0x00FF0000) >> 16;
   int green2 = (value2 & 0x0000FF00) >> 8;
   int blue2 = (value2 & 0x000000FF);
   int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) << 24)
     | ((int) (red1 * (1.0 - distance) + red2 * distance) << 16)
     | ((int) (green1 * (1.0 - distance) + green2 * distance) << 8)
     | (int) (blue1 * (1.0 - distance) + blue2 * distance);
   return rgb;
 }
 /**
  * Determines if the image has transparent pixels.
  * 
  * @param image The image to check for transparent pixel.s
  * @return true of false, according to the result
  */
 public static boolean hasAlpha(Image image)
 {
   try {
     PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
     pg.grabPixels();
     return pg.getColorModel().hasAlpha();
   }
   catch (InterruptedException e) {
     return false;
   }
 }

}</source>





Creates and returns a buffered version of the specified image.

   <source lang="java">

import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage;

public class ImageUtil {

 /**
  * Creates and returns a buffered version of the specified image.
  *
  * @param image the image to create a buffered image for
  * @return a buffered image based on the specified image
  */
 public static BufferedImage getBufferedImage(Image image) {
   BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
       BufferedImage.TYPE_INT_ARGB);
   Graphics g = bufferedImage.getGraphics();
   g.drawImage(image, 0, 0, null);
   return bufferedImage;
 }


}</source>





Create Translucent Image

   <source lang="java">

/*

* Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.GraphicsEnvironment; import java.awt.Transparency; import java.awt.image.BufferedImage; /**

* 
* @author aim
*/

public class Utils {

 public static BufferedImage createTranslucentImage(int width, int height) {
   
   return GraphicsEnvironment.getLocalGraphicsEnvironment().
               getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
          

} }</source>





Creating a Buffered Image from an Image

   <source lang="java">

import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage img = toBufferedImage(new ImageIcon("a.png").getImage());
 }
 public static BufferedImage toBufferedImage(Image image) {
   image = new ImageIcon(image).getImage();
   BufferedImage bimage = new BufferedImage(image.getWidth(null), image
       .getHeight(null), BufferedImage.TYPE_INT_ARGB);
   Graphics g = bimage.createGraphics();
   g.drawImage(image, 0, 0, null);
   g.dispose();
   return bimage;
 }

}</source>





Creating a BufferedImage from an Image object

   <source lang="java">

import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class Main {

 public static void main(String[] argv) throws Exception {
   Image  img = new ImageIcon("test.png").getImage();
   BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null),
       BufferedImage.TYPE_INT_RGB);
   Graphics g = bufferedImage.createGraphics();
   g.drawImage(img, 0, 0, null);
   g.dispose();
   ImageIO.write(bufferedImage, "png", new File("a.png"));
 }

}</source>





Creating a buffered image using Component.createImage().

   <source lang="java">

//use only if the component is visible on the screen. //It returns buffered images that do not support transparent pixels. import java.awt.image.BufferedImage; import javax.swing.JFrame; public class Main {

 public static void main(String[] argv) throws Exception {
   JFrame f = new JFrame();
   f.setVisible(true);
   int width = 300;
   int height = 500;
   BufferedImage bimage = (BufferedImage) f.createImage(width, height);
   if (bimage == null) {
     System.out.println("component is not visible on the screen");
   }
 }

}</source>





Creating a Image Zoomer using Graphics2D

   <source lang="java">

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import javax.swing.JPanel; class ImagePanel extends JPanel {

 private double zoom = 1.0;
 private double percentage;
 private Image image;
 public ImagePanel(Image image, double zoomPercentage) {
   this.image = image;
   percentage = zoomPercentage / 100;
 }
 public void paintComponent(Graphics grp) {
   Graphics2D g2D = (Graphics2D) grp;
   g2D.scale(zoom, zoom);
   g2D.drawImage(image, 0, 0, this);
 }
 public void setZoomPercentage(int zoomPercentage) {
   percentage = ((double) zoomPercentage) / 100;
 }
 public void originalSize() {
   zoom = 1;
 }
 public void zoomIn() {
   zoom += percentage;
 }
 public void zoomOut() {
   zoom -= percentage;
   if (zoom < percentage) {
     if (percentage > 1.0) {
       zoom = 1.0;
     } else {
       zoomIn();
     }
   }
 }

}</source>





Drawing on a Buffered Image

   <source lang="java">

import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; public class BasicShapes {

 public static void main(String[] args) {
   BufferedImage bimage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   Graphics2D g2d = bimage.createGraphics();
   g2d.setColor(Color.red);
   g2d.fill(new Ellipse2D.Float(0, 0, 200, 100));
   g2d.dispose();
 }

}</source>





Flipping a Buffered Image

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
   tx.translate(0, -bufferedImage.getHeight(null));
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Flip the image horizontally

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
   tx.translate(-bufferedImage.getWidth(null), 0);
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Flip the image vertically and horizontally, equivalent to rotating the image 180 degrees

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = AffineTransform.getScaleInstance(-1, -1);
   tx.translate(-bufferedImage.getWidth(null), -bufferedImage.getHeight(null));
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Getting and Setting Pixels in a Buffered Image

   <source lang="java">

import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_INT_RGB);
   int rgb = bufferedImage.getRGB(1, 1);
   int w = bufferedImage.getWidth(null);
   int h = bufferedImage.getHeight(null);
   int[] rgbs = new int[w * h];
   bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w);
   rgb = 0xFF00FF00; // green
   bufferedImage.setRGB(1, 1, rgb);
 }

}</source>





If the buffered image supports transparency

   <source lang="java">

import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class BasicShapes extends JPanel {

 public void paint(Graphics g) {
   BufferedImage bimage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   Graphics2D g2d = bimage.createGraphics();
   Color transparent = new Color(0, 0, 0, 0);
   g2d.setColor(transparent);
   g2d.setComposite(AlphaComposite.Src);
   g2d.fill(new Rectangle2D.Float(20, 20, 100, 20));
   g2d.dispose();
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Basic Shapes");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new BasicShapes());
   frame.setSize(350, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }

}</source>





If the image has transparent pixels

   <source lang="java">

/*

* Copyright (c) JForum Team
* All rights reserved.
* Redistribution and use in source and binary forms, 
* with or without modification, are permitted provided 
* that the following conditions are met:
* 1) Redistributions of source code must retain the above 
* copyright notice, this list of conditions and the 
* following  disclaimer.
* 2)  Redistributions in binary form must reproduce the 
* above copyright notice, this list of conditions and 
* the following disclaimer in the documentation and/or 
* other materials provided with the distribution.
* 3) Neither the name of "Rafael Steil" nor 
* the names of its contributors may be used to endorse 
* or promote products derived from this software without 
* specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
* IN CONTRACT, STRICT LIABILITY, OR TORT 
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
* 
* This file creation date: 21/04/2004 - 19:54:16
* The JForum Project
* http://www.jforum.net
*/

import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.PixelGrabber; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Locale; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream;

/**

* Utilities methods for image manipulation. It does not support writting of GIF images, but it can
* read from. GIF images will be saved as PNG.
* 
* @author Rafael Steil
* @version $Id: ImageUtils.java,v 1.23 2007/09/09 01:05:22 rafaelsteil Exp $
*/

public class ImageUtils {

 public static final int IMAGE_UNKNOWN = -1;
 public static final int IMAGE_JPEG = 0;
 public static final int IMAGE_PNG = 1;
 public static final int IMAGE_GIF = 2;
 /**
  * Resizes an image
  * 
  * @param imgName The image name to resize. Must be the complet path to the file
  * @param type int
  * @param maxWidth The image"s max width
  * @param maxHeight The image"s max height
  * @return A resized BufferedImage
  */
 public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight)
 {
   try {
     return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Resizes an image.
  * 
  * @param image
  *            The image to resize
  * @param maxWidth
  *            The image"s max width
  * @param maxHeight
  *            The image"s max height
  * @return A resized BufferedImage
  * @param type
  *            int
  */
 public static BufferedImage resizeImage(BufferedImage image, int type, int maxWidth, int maxHeight)
 {
   Dimension largestDimension = new Dimension(maxWidth, maxHeight);
   // Original size
   int imageWidth = image.getWidth(null);
   int imageHeight = image.getHeight(null);
   float aspectRatio = (float) imageWidth / imageHeight;
   if (imageWidth > maxWidth || imageHeight > maxHeight) {
     if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
       largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio);
     }
     else {
       largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio);
     }
     imageWidth = largestDimension.width;
     imageHeight = largestDimension.height;
   }
   return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight);
 }
 /**
  * Saves an image to the disk.
  * 
  * @param image  The image to save
  * @param toFileName The filename to use
  * @param type The image type. Use ImageUtils.IMAGE_JPEG to save as JPEG images,
  *  or ImageUtils.IMAGE_PNG to save as PNG.
  * @return false if no appropriate writer is found
  */
 public static boolean saveImage(BufferedImage image, String toFileName, int type)
 {
   try {
     return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Compress and save an image to the disk. Currently this method only supports JPEG images.
  * 
  * @param image The image to save
  * @param toFileName The filename to use
  * @param type The image type. Use ImageUtils.IMAGE_JPEG to save as JPEG images,
  * or ImageUtils.IMAGE_PNG to save as PNG.
  */
 public static void saveCompressedImage(BufferedImage image, String toFileName, int type)
 {
   try {
     if (type == IMAGE_PNG) {
       throw new UnsupportedOperationException("PNG compression not implemented");
     }
     Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
     ImageWriter writer;
     writer = (ImageWriter) iter.next();
     ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
     writer.setOutput(ios);
     ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
     iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     iwparam.setCompressionQuality(0.7F);
     writer.write(null, new IIOImage(image, null, null), iwparam);
     ios.flush();
     writer.dispose();
     ios.close();
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * Creates a BufferedImage from an Image. This method can
  * function on a completely headless system. This especially includes Linux and Unix systems
  * that do not have the X11 libraries installed, which are required for the AWT subsystem to
  * operate. This method uses nearest neighbor approximation, so it"s quite fast. Unfortunately,
  * the result is nowhere near as nice looking as the createHeadlessSmoothBufferedImage method.
  * 
  * @param image  The image to convert
  * @param w The desired image width
  * @param h The desired image height
  * @return The converted image
  * @param type int
  */
 public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width, int height)
 {
   if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
     type = BufferedImage.TYPE_INT_ARGB;
   }
   else {
     type = BufferedImage.TYPE_INT_RGB;
   }
   BufferedImage bi = new BufferedImage(width, height, type);
   for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
       bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
     }
   }
   return bi;
 }
 /**
  * Creates a BufferedImage from an Image. This method can
  * function on a completely headless system. This especially includes Linux and Unix systems
  * that do not have the X11 libraries installed, which are required for the AWT subsystem to
  * operate. The resulting image will be smoothly scaled using bilinear filtering.
  * 
  * @param source The image to convert
  * @param w The desired image width
  * @param h The desired image height
  * @return The converted image
  * @param type  int
  */
 public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type, int width, int height)
 {
   if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
     type = BufferedImage.TYPE_INT_ARGB;
   }
   else {
     type = BufferedImage.TYPE_INT_RGB;
   }
   BufferedImage dest = new BufferedImage(width, height, type);
   int sourcex;
   int sourcey;
   double scalex = (double) width / source.getWidth();
   double scaley = (double) height / source.getHeight();
   int x1;
   int y1;
   double xdiff;
   double ydiff;
   int rgb;
   int rgb1;
   int rgb2;
   for (int y = 0; y < height; y++) {
     sourcey = y * source.getHeight() / dest.getHeight();
     ydiff = scale(y, scaley) - sourcey;
     for (int x = 0; x < width; x++) {
       sourcex = x * source.getWidth() / dest.getWidth();
       xdiff = scale(x, scalex) - sourcex;
       x1 = Math.min(source.getWidth() - 1, sourcex + 1);
       y1 = Math.min(source.getHeight() - 1, sourcey + 1);
       rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey), xdiff);
       rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);
       rgb = getRGBInterpolation(rgb1, rgb2, ydiff);
       dest.setRGB(x, y, rgb);
     }
   }
   return dest;
 }
 private static double scale(int point, double scale)
 {
   return point / scale;
 }
 private static int getRGBInterpolation(int value1, int value2, double distance)
 {
   int alpha1 = (value1 & 0xFF000000) >>> 24;
   int red1 = (value1 & 0x00FF0000) >> 16;
   int green1 = (value1 & 0x0000FF00) >> 8;
   int blue1 = (value1 & 0x000000FF);
   int alpha2 = (value2 & 0xFF000000) >>> 24;
   int red2 = (value2 & 0x00FF0000) >> 16;
   int green2 = (value2 & 0x0000FF00) >> 8;
   int blue2 = (value2 & 0x000000FF);
   int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) << 24)
     | ((int) (red1 * (1.0 - distance) + red2 * distance) << 16)
     | ((int) (green1 * (1.0 - distance) + green2 * distance) << 8)
     | (int) (blue1 * (1.0 - distance) + blue2 * distance);
   return rgb;
 }
 /**
  * Determines if the image has transparent pixels.
  * 
  * @param image The image to check for transparent pixel.s
  * @return true of false, according to the result
  */
 public static boolean hasAlpha(Image image)
 {
   try {
     PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
     pg.grabPixels();
     return pg.getColorModel().hasAlpha();
   }
   catch (InterruptedException e) {
     return false;
   }
 }

}</source>





Produces a copy of the supplied image

   <source lang="java">

/*

*
* Created on March 16, 2007, 4:34 PM
*
* Copyright 2006-2007 Nigel Hughes
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at http://www.apache.org/
* licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Transparency; import java.awt.image.BufferedImage; /**

* @author nigel
*/

public class Utils {

 /**
  * Produces a copy of the supplied image
  *
  * @param image The original image
  * @return The new BufferedImage
  */
 public static BufferedImage copyImage(BufferedImage image){
     return scaledImage(image,image.getWidth(),image.getHeight());
 } 
 /**
  * Produces a resized image that is of the given dimensions
  *
  * @param image The original image
  * @param width The desired width
  * @param height The desired height
  * @return The new BufferedImage
  */
 public static BufferedImage scaledImage(BufferedImage image, int width, int height){
     BufferedImage newImage = createCompatibleImage(width,height);
     Graphics graphics = newImage.createGraphics();
     
     graphics.drawImage(image,0,0,width,height,null);
     
     graphics.dispose();
     return newImage;
 }
 /**
  * Creates an image compatible with the current display
  * 
  * @return A BufferedImage with the appropriate color model
  */
 public static BufferedImage createCompatibleImage(int width, int height) {
   GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment()
       .getDefaultScreenDevice().getDefaultConfiguration();
   return configuration.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
 }

}</source>





Produces a resized image that is of the given dimensions

   <source lang="java">

/*

*
* Created on March 16, 2007, 4:34 PM
*
* Copyright 2006-2007 Nigel Hughes
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at http://www.apache.org/
* licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Transparency; import java.awt.image.BufferedImage; /**

* @author nigel
*/

public class Utils {

 /**
  * Produces a resized image that is of the given dimensions
  *
  * @param image The original image
  * @param width The desired width
  * @param height The desired height
  * @return The new BufferedImage
  */
 public static BufferedImage scaledImage(BufferedImage image, int width, int height){
     BufferedImage newImage = createCompatibleImage(width,height);
     Graphics graphics = newImage.createGraphics();
     
     graphics.drawImage(image,0,0,width,height,null);
     
     graphics.dispose();
     return newImage;
 }
 /**
  * Creates an image compatible with the current display
  * 
  * @return A BufferedImage with the appropriate color model
  */
 public static BufferedImage createCompatibleImage(int width, int height) {
   GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment()
       .getDefaultScreenDevice().getDefaultConfiguration();
   return configuration.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
 }

}</source>





Rotating a Buffered Image

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = new AffineTransform();
   tx.rotate(0.5, bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_BILINEAR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Scaling a Buffered Image

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = new AffineTransform();
   tx.scale(1, 2);
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_BILINEAR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Shearing a Buffered Image

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = new AffineTransform();
   tx.shear(2, 3);
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_BILINEAR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





Translating a Buffered Image

   <source lang="java">

import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   BufferedImage bufferedImage = new BufferedImage(200, 200,
       BufferedImage.TYPE_BYTE_INDEXED);
   AffineTransform tx = new AffineTransform();
   tx.translate(2, 1);
   AffineTransformOp op = new AffineTransformOp(tx,
       AffineTransformOp.TYPE_BILINEAR);
   bufferedImage = op.filter(bufferedImage, null);
 }

}</source>





TYPE_INT_RGB and TYPE_INT_ARGB are typically used

   <source lang="java">

import java.awt.image.BufferedImage; public class Main {

 public static void main(String[] argv) throws Exception {
   int width = 100;
   int height = 100;
   BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
 }

}</source>