Image Operations : Image « 2D Graphics GUI « Java

Image Operations

Image Operations
 * 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

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
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 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() { imageurl = this.getClass().getResource("cover.gif");
    image = new javax.swing.ImageIcon(imageurl).getImage();

  // 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
      // 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,
      // 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(; // 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);
        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) {
    f.setContentPane(new ImageOps());


Related examples in the same category

1.Image size Image size
2.Image demoImage demo
3.Getting the Color Model of an Image
4.Filtering the RGB Values in an Image
5.Create a filter that can modify any of the RGB pixel values in an image.
6.This filter removes all but the red values in an image
7.Load and draw image
8.Paint an IconPaint an Icon
9.Image Processing: Brightness and ContrastImage Processing: Brightness and Contrast
10.Image with mouse drag and move eventImage with mouse drag and move event
11.Image Animation and ThreadImage Animation and Thread
12.Image Color Gray EffectImage Color Gray Effect
13.Image BufferingImage Buffering
14.Image Effect: CombineImage Effect: Combine
15.AffineTransform demoAffineTransform demo
16.Image Effect: Rotate Image using DataBufferImage Effect: Rotate Image using DataBuffer
17.Image Effect: Sharpen, blurImage Effect: Sharpen, blur
18.Image scale
19.Image crop
20.Demonstrating the Drawing of an Image with a Convolve Operation
21.Demonstrating Use of the Image I/O Library
22.Adding Image-Dragging Behavior
23.Sending Image Objects through the ClipboardSending Image Objects through the Clipboard
24.Anti AliasAnti Alias
25.Image ViewerImage Viewer
26.Get the dimensions of the image; these will be non-negative
27.Standalone Image Viewer - works with any AWT-supported format
28.Toolkit.getImage() which works the same in either Applet or Application
29.Double Buffered Image
30.Graband Fade: displays image and fades to black
31.Graband Fade with Rasters
32.Rotate Image 45 Degrees
33.Convert java.awt.image.BufferedImage to java.awt.Image
34.Filter image by multiplier its red, green and blue color
35.Drags within the imageDrags within the image
36.TYPE_INT_RGB and TYPE_INT_ARGB are typically used
37.Pixels from a buffered image can be modified
38.Calculation of the mean value of an image with Raster
39.Use PixelGrabber class to acquire pixel data from an Image object
40.Flip an image
41.Rendered Image
42.Image Panel
43.Image Utils
44.Returns an image resource.
45.Create Gradient Image
46.Create Gradient Mask
47.Create Translucent Image
48.Make Raster Writable
49.A frame that displays an image
50.Optimized version of copyData designed to work on Integer packed data with a SinglePixelPackedSampleModel
51.Various image processing operations.Various image processing operations.
52.This program demonstrates the transfer of images between a Java application and the system clipboard.This program demonstrates the transfer of images between a Java application and the system clipboard.
53.Scales down an image into a box of maxSideLenght x maxSideLength.
54.Adding watermark to an image
55.Scale Image
56.Crop Image
57.Fit Image
58.Converts a java.awt.Image into an array of pixels
59.Creates a scaled copy of the source image.
60.Provides useful methods for converting images from one colour depth to another.
61.Reads an image in a file and creates a thumbnail in another file.
62.Make image TransparencyMake image Transparency
63.Clips the input image to the specified shape
64.Image Sorter frame
65.Returns an ImageIcon, or null if the path was invalid.
66.Create new image from source image
67.check if image supported
68.Get supported image format
69.get image thumbnail
70.get image orientation type
71.get fixing preview image