Java Tutorial/2D Graphics/Image

Материал из Java эксперт
Версия от 15:25, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A 3x3 kernel that blurs an image.

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(200, 200,
        BufferedImage.TYPE_BYTE_INDEXED);
    Kernel kernel = new Kernel(3, 3, new float[] { 1f / 9f, 1f / 9f, 1f / 9f,
        1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f });
    BufferedImageOp op = new ConvolveOp(kernel);
    bufferedImage = op.filter(bufferedImage, null);
  }
}





A 3x3 kernel that embosses an image.

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(200, 200,
        BufferedImage.TYPE_BYTE_INDEXED);
    Kernel kernel = new Kernel(3, 3, new float[] { -2, 0, 0, 0, 1, 0, 0, 0, 2 });
    BufferedImageOp op = new ConvolveOp(kernel);
    bufferedImage = op.filter(bufferedImage, null);
  }
}





A 3x3 kernel that sharpens an image.

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(200, 200,
        BufferedImage.TYPE_BYTE_INDEXED);
    Kernel kernel = new Kernel(3, 3, new float[] { -1, -1, -1, -1, 9, -1, -1,
        -1, -1 });
    BufferedImageOp op = new ConvolveOp(kernel);
    bufferedImage = op.filter(bufferedImage, null);
  }
}





A reflected image: effect makes an illusion as if the image was reflected in water

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ImageReflection extends JComponent {
  public void paintComponent(Graphics g) {
    try {
      BufferedImage image = ImageIO.read(new File("yourImage.jpg"));
      Graphics2D g2d = (Graphics2D) g;
      int width = getWidth();
      int height = getHeight();
      int imageWidth = image.getWidth();
      int imageHeight = image.getHeight();
      int gap = 20;
      float opacity = 0.4f;
      float fadeHeight = 0.3f;
      g2d.translate((width - imageWidth) / 2, height / 2 - imageHeight);
      g2d.drawRenderedImage(image, null);
      g2d.translate(0, 2 * imageHeight + gap);
      g2d.scale(1, -1);
      BufferedImage reflection = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
      Graphics2D rg = reflection.createGraphics();
      rg.drawRenderedImage(image, null);
      rg.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN));
      rg.setPaint(new GradientPaint(0, imageHeight * fadeHeight, new Color(0.0f, 0.0f, 0.0f, 0.0f),
          0, imageHeight, new Color(0.0f, 0.0f, 0.0f, opacity)));
      rg.fillRect(0, 0, imageWidth, imageHeight);
      rg.dispose();
      g2d.drawRenderedImage(reflection, null);
    } catch (Exception e) {
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Reflection");
    ImageReflection r = new ImageReflection();
    frame.add(r);
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Blur our image: Blur means an unfocused image

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BlurredImage extends JPanel {
  public void paint(Graphics g) {
    try {
      BufferedImage myImage = ImageIO.read(this.getClass().getResource("redrock.png"));
      BufferedImage filteredImage = new BufferedImage(myImage.getWidth(null), myImage
          .getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
      Graphics g1 = filteredImage.getGraphics();
      g1.drawImage(myImage, 400, 200, null);
      float[] blurKernel = { 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f, 1 / 9f };
      BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel));
      myImage = blur.filter(myImage, null);
      g1.dispose();
      Graphics2D g2d = (Graphics2D) g;
      g2d.drawImage(myImage, null, 3, 3);
    } catch (Exception e) {
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Blurred Image");
    frame.add(new BlurredImage());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Brighten the image by 30%

import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(200, 200,
        BufferedImage.TYPE_BYTE_INDEXED);
    float scaleFactor = 1.3f;
    RescaleOp op = new RescaleOp(scaleFactor, 0, null);
    bufferedImage = op.filter(bufferedImage, null);
  }
}





Calculation of the mean value of an image

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  public static double meanValue(BufferedImage image) {
    Raster raster = image.getRaster();
    double sum = 0.0;
    for (int y = 0; y < image.getHeight(); ++y){
      for (int x = 0; x < image.getWidth(); ++x){
        sum += raster.getSample(x, y, 0);
      }
    }
    return sum / (image.getWidth() * image.getHeight());
  }
}





Create a filter that can modify any of the RGB pixel values in an image.

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;
import javax.swing.ImageIcon;

class GetRedFilter extends RGBImageFilter {
  public GetRedFilter() {
    canFilterIndexColorModel = true;
  }
  public int filterRGB(int x, int y, int rgb) {
    if (x == -1) {
    }
    return rgb & 0xffff0000;
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("image.gif").getImage();
    ImageFilter filter = new GetRedFilter();
    FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter);
    image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
  }
}





Create a grayscale image with Java 2D tools

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GrayImage extends JPanel {
  public GrayImage() {
  }
  public void paint(Graphics g) {
    Image myImage = new ImageIcon("yourImage.png").getImage();
    BufferedImage bufferedImage = new BufferedImage(myImage.getHeight(this), myImage.getWidth(this), BufferedImage.TYPE_BYTE_GRAY);
    Graphics gi = bufferedImage.getGraphics();
    gi.drawImage(myImage, 0, 0, null);
    gi.dispose();
    
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(bufferedImage, null, 0, 0);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new GrayImage());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Creates PNG images of the specified color that fade from fully opaque to fully transparent

/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
import java.io.*;
import java.awt.*;
import java.awt.image.*;
/*
 * This program creates PNG images of the specified color that fade from fully
 * opaque to fully transparent. Images of this sort are useful in web design
 * where they can be used as background images and combined with background
 * colors to produce two-color fades. (IE6 does not support PNG transparency).
 * 
 * Images are produced in three sizes and with and 8 directions. The images are
 * written into the current directory and are given names of the form:
 * fade-to-color-speed-direction.png
 * 
 * color: the color name specified on the command line speed: slow (1024px),
 * medium (512px), fast(256px) direction: a compass point: N, E, S, W, NE, SE,
 * SW, NW
 * 
 * Invoke this program with a color name and three floating-point values
 * specifying the red, green, and blue components of the color.
 */
public class MakeFades {
  // A fast fade is a small image, and a slow fade is a large image
  public static final String[] sizeNames = { "fast", "medium", "slow" };
  public static final int[] sizes = { 256, 512, 1024 };
  // Direction names and coordinates
  public static final String[] directionNames = { "N", "E", "S", "W", "NE", "SE", "SW", "NW" };
  public static float[][] directions = { new float[] { 0f, 1f, 0f, 0f }, // North
      new float[] { 0f, 0f, 1f, 0f }, // East
      new float[] { 0f, 0f, 0f, 1f }, // South
      new float[] { 1f, 0f, 0f, 0f }, // West
      new float[] { 0f, 1f, 1f, 0f }, // Northeast
      new float[] { 0f, 0f, 1f, 1f }, // Southeast
      new float[] { 1f, 0f, 0f, 1f }, // Southwest
      new float[] { 1f, 1f, 0f, 0f } // Northwest
  };
  public static void main(String[] args) throws IOException, NumberFormatException {

    // Create from and to colors based on those arguments
    Color from = Color.RED; // transparent
    Color to = Color.BLACK; // opaque
    // Loop through the sizes and directions, and create an image for each
    for (int s = 0; s < sizes.length; s++) {
      for (int d = 0; d < directions.length; d++) {
        // This is the size of the image
        int size = sizes[s];
        // Create a GradientPaint for this direction and size
        Paint paint = new GradientPaint(directions[d][0] * size, directions[d][1] * size, from,
            directions[d][2] * size, directions[d][3] * size, to);
        // Start with a blank image that supports transparency
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        // Now use fill the image with our color gradient
        Graphics2D g = image.createGraphics();
        g.setPaint(paint);
        g.fillRect(0, 0, size, size);
        // This is the name of the file we"ll write the image to
        File file = new File("fade-to-" + sizeNames[s] + "-" + directionNames[d]
            + ".png");
        // Save the image in PNG format using the javax.imageio API
        javax.imageio.ImageIO.write(image, "png", file);
        // Show the user our progress by printing the filename
        System.out.println(file);
      }
    }
  }
}





Darken the image by 10%

import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(200, 200,
        BufferedImage.TYPE_BYTE_INDEXED);
    RescaleOp op = new RescaleOp(.9f, 0, null);
    bufferedImage = op.filter(bufferedImage, null);
  }
}





Determining If an Image Has Transparent Pixels

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import javax.swing.ImageIcon;
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("a.png").getImage();
    if (image instanceof BufferedImage) {
      BufferedImage bimage = (BufferedImage) image;
      System.out.println(bimage.getColorModel().hasAlpha());
    }
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
    }
    ColorModel cm = pg.getColorModel();
    System.out.println(cm.hasAlpha());
  }
}





Draw an Icon object

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    ImageIcon icon = new ImageIcon("a.png");
    int x = 0;
    int y = 100;
    icon.paintIcon(this, g, x, y);
  }
}





Draw Image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Image img1 = Toolkit.getDefaultToolkit().getImage("yourFile.gif");
    g2.drawImage(img1, 10, 10, this);
    g2.finalize();
  }
}
public class Graphics2DDrawImage {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Enlarging an image by pixel replication

import java.awt.image.BufferedImage;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  public static BufferedImage enlarge(BufferedImage image, int n) {
    int w = n * image.getWidth();
    int h = n * image.getHeight();
    BufferedImage enlargedImage = new BufferedImage(w, h, image.getType());
    for (int y = 0; y < h; ++y){
      for (int x = 0; x < w; ++x){
        enlargedImage.setRGB(x, y, image.getRGB(x / n, y / n));
      }
    }
    return enlargedImage;
  }
}





Filtering the RGB Values in an Image

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;
import javax.swing.ImageIcon;

class GetRedFilter extends RGBImageFilter {
  public GetRedFilter() {
    canFilterIndexColorModel = true;
  }
  public int filterRGB(int x, int y, int rgb) {
    if (x == -1) {
    }
    return rgb & 0xffff0000;
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("image.gif").getImage();
    ImageFilter filter = new GetRedFilter();
    FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter);
    image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
  }
}





Flip an image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageFlip extends JPanel {
  public void paint(Graphics g) {
    Image myImage = new ImageIcon("yourImage.jpg").getImage();
    BufferedImage bufferedImage = new BufferedImage(myImage.getWidth(null), myImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) g;
    Graphics gb = bufferedImage.getGraphics();
    gb.drawImage(myImage, 0, 0, null);
    gb.dispose();
    AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
    tx.translate(-myImage.getWidth(null), 0);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    bufferedImage = op.filter(bufferedImage, null);
    g2d.drawImage(myImage, 10, 10, null);
    g2d.drawImage(bufferedImage, null, 300, 10);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Flip image");
    frame.add(new ImageFlip());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(570, 230);
    frame.setVisible(true);
  }
}





Flush an image

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Event;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
public class flushMe extends Frame {
  Image im;
  flushMe() {
    super("Flushing");
    im = Toolkit.getDefaultToolkit().getImage("flush.gif");
    setSize(175, 225);
  }
  public void paint(Graphics g) {
    g.drawImage(im, 0, 0, 175, 225, this);
  }
  public boolean mouseDown(Event e, int x, int y) {
    im.flush();
    repaint();
    return true;
  }
  public static void main(String[] args) {
    Frame f = new flushMe();
    f.setVisible(true);
  }
}





Get average of a set of images

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
public class Main {
  static BufferedImage average(BufferedImage[] images) {
    BufferedImage average = new BufferedImage(images[0].getWidth(), images[0].getHeight(),
        BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster raster = average.getRaster().createCompatibleWritableRaster();
    for (int k = 0; k < images[0].getHeight(); ++k) {
      for (int j = 0; j < images[0].getWidth(); ++j) {
        float sum = 0.0f;
        for (int i = 0; i < images.length; ++i) {
          sum = sum + images[i].getRaster().getSample(j, k, 0);
        }
        raster.setSample(j, k, 0, Math.round(sum / images.length));
      }
    }
    average.setData(raster);
    return average;
  }
}





Get the dimensions of the image; these will be non-negative

import java.awt.Image;
import java.awt.Toolkit;
public class BasicDraw {
  public static void main(String[] args) {
    Image image = new ImageIcon("image.gif").getImage();
    
    width = image.getWidth(null);
    height = image.getHeight(null);
  }
}





Getting the Color Model of an Image

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import javax.swing.ImageIcon;
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("a.png").getImage();
    if (image instanceof BufferedImage) {
      BufferedImage bimage = (BufferedImage) image;
      System.out.println(bimage.getColorModel().getNumColorComponents());
    }
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
    }
    ColorModel cm = pg.getColorModel();
    System.out.println(cm.getNumColorComponents());
  }
}





Gray scale image operation

/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.ru/javaexamples2.
 */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ByteLookupTable;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.RescaleOp;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** A demonstration of various image processing filters */
public class ImageOps extends JPanel {
    static final int WIDTH = 600, HEIGHT = 675; // Size of our example
    public String getName() {
        return "Image Processing";
    }
    public int getWidth() {
        return WIDTH;
    }
    public int getHeight() {
        return HEIGHT;
    }
    Image image;
    /** This constructor loads the image we will manipulate */
public ImageOps() {
    image = Toolkit.getDefaultToolkit().getImage("a.jpg");
  }
    // These arrays of bytes are used by the LookupImageOp image filters below
    static byte[] brightenTable = new byte[256];
    static byte[] thresholdTable = new byte[256];
    static { // Initialize the arrays
        for (int i = 0; i < 256; i++) {
            brightenTable[i] = (byte) (Math.sqrt(i / 255.0) * 255);
            thresholdTable[i] = (byte) ((i < 225) ? 0 : i);
        }
    }
    // This AffineTransform is used by one of the image filters below
    static AffineTransform mirrorTransform;
    static { // Create and initialize the AffineTransform
        mirrorTransform = AffineTransform.getTranslateInstance(127, 0);
        mirrorTransform.scale(-1.0, 1.0); // flip horizontally
    }
    // These are the labels we"ll display for each of the filtered images
    static String[] filterNames = new String[] { "Original", "Gray Scale", "Negative", "Brighten (linear)", "Brighten (sqrt)", "Threshold", "Blur", "Sharpen", "Edge Detect", "Mirror", "Rotate (center)", "Rotate (lower left)" };
    // The following BufferedImageOp image filter objects perform
    // different types of image processing operations.
    static BufferedImageOp[] filters = new BufferedImageOp[] {
    // 1) No filter here. We"ll display the original image
                                                              null,
                                                              // 2) Convert to Grayscale color space
                                                              new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null),
                                                              // 3) Image negative. Multiply each color value by -1.0 and add 255
                                                              new RescaleOp(-1.0f, 255f, null),
                                                              // 4) Brighten using a linear formula that increases all color
                                                              // values
                                                              new RescaleOp(1.25f, 0, null),
                                                              // 5) Brighten using the lookup table defined above
                                                              new LookupOp(new ByteLookupTable(0, brightenTable), null),
                                                              // 6) Threshold using the lookup table defined above
                                                              new LookupOp(new ByteLookupTable(0, thresholdTable), null),
                                                              // 7) Blur by "convolving" the image with a matrix
                                                              new ConvolveOp(new Kernel(3, 3, new float[] { .1111f, .1111f, .1111f, .1111f, .1111f, .1111f, .1111f, .1111f, .1111f, })),
                                                              // 8) Sharpen by using a different matrix
                                                              new ConvolveOp(new Kernel(3, 3, new float[] { 0.0f, -0.75f, 0.0f, -0.75f, 4.0f, -0.75f, 0.0f, -0.75f, 0.0f })),
                                                              // 9) Edge detect using yet another matrix
                                                              new ConvolveOp(new Kernel(3, 3, new float[] { 0.0f, -0.75f, 0.0f, -0.75f, 3.0f, -0.75f, 0.0f, -0.75f, 0.0f })),
                                                              // 10) Compute a mirror image using the transform defined above
                                                              new AffineTransformOp(mirrorTransform, AffineTransformOp.TYPE_BILINEAR),
                                                              // 11) Rotate the image 180 degrees about its center point
                                                              new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI, 64, 95), AffineTransformOp.TYPE_NEAREST_NEIGHBOR),
                                                              // 12) Rotate the image 15 degrees about the bottom left
                                                              new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 12, 0, 190), AffineTransformOp.TYPE_NEAREST_NEIGHBOR), };
    /** Draw the example */
    public void paint(Graphics g1) {
        Graphics2D g = (Graphics2D) g1;
        // Create a BufferedImage big enough to hold the Image loaded
        // in the constructor. Then copy that image into the new
        // BufferedImage object so that we can process it.
        BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this), BufferedImage.TYPE_INT_RGB);
        Graphics2D ig = bimage.createGraphics();
        ig.drawImage(image, 0, 0, this); // copy the image
        // Set some default graphics attributes
        g.setFont(new Font("SansSerif", Font.BOLD, 12)); // 12pt bold text
        g.setColor(Color.green); // Draw in green
        g.translate(10, 10); // Set some margins
        // Loop through the filters
        for (int i = 0; i < filters.length; i++) {
            // If the filter is null, draw the original image, otherwise,
            // draw the image as processed by the filter
            if (filters[i] == null)
                g.drawImage(bimage, 0, 0, this);
            else
                g.drawImage(filters[i].filter(bimage, null), 0, 0, this);
            g.drawString(filterNames[i], 0, 205); // Label the image
            g.translate(137, 0); // Move over
            if (i % 4 == 3)
                g.translate(-137 * 4, 215); // Move down after 4
        }
    }
    public static void main(String[] a) {
        JFrame f = new JFrame();
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setContentPane(new ImageOps());
        f.pack();
        f.setVisible(true);
    }
}





Load Image and scale it

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageFileFilterImageScale extends JFrame implements ActionListener {
  Image img;
  JButton getPictureButton  = new JButton("Get Picture");
  public static void main(String[] args) {
    new ImageFileFilterImageScale();
  }
  public ImageFileFilterImageScale() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel picPanel = new PicturePanel();
    this.add(picPanel, BorderLayout.CENTER);
    JPanel buttonPanel = new JPanel();
    getPictureButton.addActionListener(this);
    buttonPanel.add(getPictureButton);
    this.add(buttonPanel, BorderLayout.SOUTH);
    this.setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    String file = getImageFile();
    if (file != null) {
      Toolkit kit = Toolkit.getDefaultToolkit();
      img = kit.getImage(file);
      img = img.getScaledInstance(300, -1, Image.SCALE_SMOOTH);
      this.repaint();
    }
  }
  private String getImageFile() {
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new ImageFilter());
    int result = fc.showOpenDialog(null);
    File file = null;
    if (result == JFileChooser.APPROVE_OPTION) {
      file = fc.getSelectedFile();
      return file.getPath();
    } else
      return null;
  }
  class PicturePanel extends JPanel {
    public void paint(Graphics g) {
      g.drawImage(img, 0, 0, this);
    }
  }
}
class ImageFilter extends javax.swing.filechooser.FileFilter {
  public boolean accept(File f) {
    if (f.isDirectory())
      return true;
    String name = f.getName();
    if (name.matches(".*((.jpg)|(.gif)|(.png))"))
      return true;
    else
      return false;
  }
  public String getDescription() {
    return "Image files (*.jpg, *.gif, *.png)";
  }
}





Reading an Image or Icon from a File

import java.awt.Image;
import java.awt.Toolkit;
public class BasicDraw {
  public static void main(String[] args) {
    Image image = Toolkit.getDefaultToolkit().getImage("image.gif");
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    if (width >= 0) {
      // The image has been fully loaded
    } else {
      // The image has not been fully loaded
    }
  }
}





Resize an image

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Image img1 = Toolkit.getDefaultToolkit().getImage("yourFile.gif");
    int width = img1.getWidth(this);
    int height = img1.getHeight(this);
    int scale = 2;
    int w = scale * width;
    int h = scale * height;
    // explicitly specify width (w) and height (h)
    g.drawImage(img1, 10, 10, (int) w, (int) h, this);
  }
}
public class Graphics2DDrawScaleImage {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Rotating a Drawn Image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform tx = new AffineTransform();
    double radians = -Math.PI / 4;
    tx.rotate(radians);
    g2d.setTransform(tx);
    g2d.drawImage(new ImageIcon("a.png").getImage(), tx, this);
  }
}





Scaling a Drawn Image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform tx = new AffineTransform();
    double scalex = .5;
    double scaley = 1;
    tx.scale(scalex, scaley);
    g2d.setTransform(tx);
    g2d.drawImage(new ImageIcon("a.png").getImage(), tx, this);
  }
}





Shearing a Drawn Image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform tx = new AffineTransform();
    double shiftx = .1;
    double shifty = .3;
    tx.shear(shiftx, shifty);
    g2d.setTransform(tx);
    g2d.drawImage(new ImageIcon("a.png").getImage(), tx, this);
  }
}





Shrinking an image by skipping pixels

import java.awt.image.BufferedImage;
public class Main {
  static BufferedImage enlarge(BufferedImage image, int n) {
    int w = image.getWidth() / n;
    int h = image.getHeight() / n;
    BufferedImage shrunkImage = new BufferedImage(w, h, image.getType());
    for (int y = 0; y < h; ++y)
      for (int x = 0; x < w; ++x)
        shrunkImage.setRGB(x, y, image.getRGB(x * n, y * n));
    return shrunkImage;
  }
}





This filter removes all but the red values in an image

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;
import javax.swing.ImageIcon;

class GetRedFilter extends RGBImageFilter {
  public GetRedFilter() {
    canFilterIndexColorModel = true;
  }
  public int filterRGB(int x, int y, int rgb) {
    if (x == -1) {
    }
    return rgb & 0xffff0000;
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Image image = new ImageIcon("image.gif").getImage();
    ImageFilter filter = new GetRedFilter();
    FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter);
    image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
  }
}





Translating a Drawn Image

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform tx = new AffineTransform();
    double x = 50;
    double y = 50;
    tx.translate(x, y);
    g2d.setTransform(tx);
    g2d.drawImage(new ImageIcon("a.png").getImage(), tx, this);
  }
}





Use PixelGrabber class to acquire pixel data from an Image object

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
public class Main {
  static boolean isGreyscaleImage(PixelGrabber pg) {
    return pg.getPixels() instanceof byte[];
  }
  public static void main(String args[]) throws Exception {
    Image image = Toolkit.getDefaultToolkit().getImage("inFile.png");
    PixelGrabber grabber = new PixelGrabber(image, 0, 0, -1, -1, false);
    if (grabber.grabPixels()) {
      int width = grabber.getWidth();
      int height = grabber.getHeight();
      if (isGreyscaleImage(grabber)) {
        byte[] data = (byte[]) grabber.getPixels();
      } else {
        int[] data = (int[]) grabber.getPixels();
      }
    }
  }
}





Using mediatracker to pre-load images

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
  Main() {
    add(BorderLayout.CENTER, new ImagePanel());
    setSize(800, 150);
  }
  public static void main(String[] args) {
    Main jrframe = new Main();
    jrframe.setVisible(true);
  }
}
class ImagePanel extends JPanel {
  String images[] = { "i.png", "j.png" };
  Image[] imgs = new Image[images.length];
  ImagePanel() {
    MediaTracker mt = new MediaTracker(this);
    for (int i = 0; i < images.length; i++) {
      imgs[i] = Toolkit.getDefaultToolkit().getImage(images[i]);
      mt.addImage(imgs[i], i);
    }
    try {
      mt.waitForAll();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    int x = 0;
    int y = 0;
    for (int i = 0; i < imgs.length; i++) {
      g.drawImage(imgs[i], x, y, null);
      x += imgs[i].getWidth(null);
    }
  }
}