Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 201 ยท Input and Output

Image Processing in Java

Read and write images with ImageIO, get and set pixels in a BufferedImage, and build grayscale, negative, sepia, color-channel, random and mirror filters in plain Java.

A digital image is a grid of colored dots called pixels. Image processing means reading that grid, changing some of the numbers, and writing the result back. Blurring a photo, turning it black and white, flipping it, or cutting out a color channel are all loops over pixels. Java has everything you need for this built in: java.awt.image.BufferedImage holds the pixels, and javax.imageio.ImageIO reads and writes common file formats such as PNG, JPEG, GIF and BMP. No libraries and no window are required, so everything in this lesson works on a server, too.

You will learn how a pixel is stored in a single int, how to read and write image files, how to get and set pixels, and then how to build six classic filters. Our runner has no screen, so the examples print small images as text (one character per pixel) and show the numbers behind them.

How a pixel is stored

A BufferedImage is a rectangle of width x height pixels. The position of a pixel is (x, y), where x counts columns from the left and y counts rows from the top. The top-left pixel is (0, 0). That's different from a math graph, where y grows upward.

TEXT
        x = 0   1   2   3
 y = 0  [0,0][1,0][2,0][3,0]
 y = 1  [0,1][1,1][2,1][3,1]
 y = 2  [0,2][1,2][2,2][3,2]      a 4 x 3 image: width = 4, height = 3

The most common pixel layout is ARGB: four numbers from 0 to 255 packed into one 32-bit int, 8 bits each:

Bits 31-24 23-16 15-8 7-0
Channel Alpha (opacity, 255 = solid) Red Green Blue

So an opaque orange pixel with red 255, green 128 and blue 0 is 0xFFFF8000. You pack and unpack the channels with the bit operators from Bitwise Operators: shift right to bring a channel to the bottom, then mask with & 0xFF to drop everything above it.

Java Packing and unpacking an ARGB pixel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Opaque pixels have alpha 255, which sets the top bit, so getRGB returns negative numbers for them. That's normal. Use >>> 24 (unsigned shift) for alpha so you get 255 instead of -1.

Creating, writing and reading images

new BufferedImage(width, height, type) makes a blank image (all pixels transparent black). The type says how pixels are stored. Two types cover almost everything:

  • BufferedImage.TYPE_INT_ARGB: with transparency (needed for PNG with see-through areas).
  • BufferedImage.TYPE_INT_RGB: no alpha channel; smaller, and the only choice for JPEG and BMP.

ImageIO.write(image, formatName, file) saves an image and returns a boolean: true if a writer for that format accepted it. ImageIO.read(file) loads an image and returns null when no reader recognizes the file. Both can throw IOException. (ImageIO.read also accepts an InputStream or a URL, and ImageIO.write an OutputStream.)

Java Write and read a PNG; the JPEG alpha trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The JPEG line prints false because there is no JPEG writer for an image with an alpha channel, and no exception is thrown. Always check the boolean that ImageIO.write returns; a silent false is the most common reason an "empty" output file appears. Drawing the ARGB image onto a TYPE_INT_RGB image (using the Graphics object of java.awt) converts it. Also remember that ImageIO.read can return null for a file it cannot decode, so check for that before using the image.

Image classes live in java.desktop, but they do not open any window. BufferedImage, ImageIO and Graphics work fine on a headless server. Only classes such as JFrame need a display (see Swing Basics).

Getting and setting pixels

Two methods do all the work:

  • int getRGB(int x, int y) returns the ARGB pixel. (The name says RGB, but alpha is included.)
  • void setRGB(int x, int y, int argb) writes one.

Pixel loops are two nested loops: the outer one over rows y, the inner one over columns x. Going row by row matches how the pixels are laid out in memory and is faster than going column by column. The programs below share a tiny helper that prints an image as text, using characters from dark to light, so you can see what each filter does.

Java Draw, read and print an image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

getRGB(x, y) is convenient but slow when called millions of times. For big images, read the whole thing at once with int[] pixels = img.getRGB(0, 0, w, h, null, 0, w), change the array, and write it back with setRGB(0, 0, w, h, pixels, 0, w). The array is row after row, so pixel (x, y) is at index y * w + x.

Filters: grayscale, negative and sepia

Every filter below follows the same recipe: loop over all pixels, unpack r, g, b, compute new values, clamp them to 0-255, and pack them again. We keep the alpha channel unchanged.

Grayscale. A gray pixel has equal red, green and blue. The simple average (r + g + b) / 3 works, but human eyes are most sensitive to green and least to blue, so the standard formula weights them: 0.299 * r + 0.587 * g + 0.114 * b.

Negative. Replace every channel c with 255 - c. Black becomes white, red becomes cyan.

Sepia. The warm brown "old photo" look mixes the three channels with a fixed matrix:

TEXT
newR = 0.393*r + 0.769*g + 0.189*b
newG = 0.349*r + 0.686*g + 0.168*b
newB = 0.272*r + 0.534*g + 0.131*b

The rows of this matrix add up to more than 1, so results can exceed 255. That is why we need Math.min(255, ...).

Java Grayscale, negative and sepia filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Pure red turns into a dark gray (0.299 * 255 = 76) under grayscale, white stays white under grayscale but becomes (255, 255, 239) under sepia (the red and green sums exceed 255 and are clamped, while blue is not), and negative flips everything. Notice how the apply helper takes the filter as a lambda (Lambda Expressions): one loop, any per-pixel rule. It always writes into a new image, so the original stays intact and you can compare before and after.

Isolating red, green and blue

To see one color channel on its own, keep that channel and set the other two to zero. Doing this for red, green and blue gives you the three "layers" every color image is made of.

Java Splitting an image into R, G and B images

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A bit mask does the job in one operation: pixel & 0xFF0000 keeps red and zeroes everything else (including alpha, which is fine for an RGB image).

A random-pixel image

For noise, test patterns or procedural art, you generate the pixel values instead of reading them. java.util.Random produces numbers; give it a seed and the "random" image is identical on every run (see Random Numbers).

Java A seeded random image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Mirroring an image

A mirror image copies each pixel to a new place. For a horizontal flip (left and right swap), pixel (x, y) goes to (width - 1 - x, y). For a vertical flip (top and bottom swap), it goes to (x, height - 1 - y). The - 1 is there because the last column has index width - 1.

Java Horizontal and vertical mirror

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You can mirror in place by swapping pairs, but writing to a second image is simpler and safer. For real work, AffineTransform/AffineTransformOp (also in java.awt) can flip and rotate in one call, and Graphics2D.drawImage can scale an image; the pixel loops here are how those tools work underneath.

Face detection and other advanced tasks

Everything above uses only the JDK. Recognizing things in a picture, such as faces, is a different level of difficulty: you need a trained model and a computer-vision library. The standard choice is OpenCV, which has Java bindings. The workflow looks like this (read-only code, because OpenCV is a native library that our runner doesn't have):

Java
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDemo {
    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);            // load the native OpenCV code

        // A trained model: Haar cascades ship as XML files with OpenCV
        CascadeClassifier detector = new CascadeClassifier("haarcascade_frontalface_default.xml");

        Mat image = Imgcodecs.imread("people.jpg");              // read (OpenCV's own Mat, not BufferedImage)
        MatOfRect faces = new MatOfRect();
        detector.detectMultiScale(image, faces);                 // find faces

        for (Rect r : faces.toArray()) {                         // draw a box around each one
            Imgproc.rectangle(image, r.tl(), r.br(), new Scalar(0, 255, 0), 3);
        }
        Imgcodecs.imwrite("people-marked.jpg", image);           // write the result
        System.out.println(faces.toArray().length + " face(s) found");
    }
}

OpenCV has its own image type, Mat, with its own read and write functions (Imgcodecs.imread and imwrite), so you convert between Mat and BufferedImage when mixing the two worlds. To use it you add the OpenCV JAR to the classpath and point the JVM at the native library. For simple image work (resize, crop, filters, format conversion), plain BufferedImage and ImageIO are usually all you need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where is the pixel (0, 0) in a BufferedImage?

    x counts columns from the left and y counts rows from the top, so (0, 0) is the top-left pixel.
  2. 2. What does ImageIO.write(argbImage, "jpg", file) return when the image has an alpha channel?

    ImageIO reports the failure with a false return value, and no file content is written. Copy the image into a TYPE_INT_RGB image first, and always check the boolean.
  3. 3. How do you compute the negative of a pixel's red value r?

    Each channel runs from 0 to 255, so inverting it is 255 - r. Black (0) becomes white (255).
  4. 4. Which expression extracts the green channel from an ARGB int p?

    Green is in bits 15-8, so shift right by 8 and mask with 0xFF. Blue is p & 0xFF, red needs a shift of 16 and alpha a shift of 24.
  5. 5. For an image of width w, to which x position does a horizontal mirror copy the pixel at x?

    The last column is w - 1, so column 0 goes to w - 1 and column w - 1 goes to 0. Using w - x would be one position too far and go out of bounds for x = 0.

Summary

  • A BufferedImage is a grid of pixels; (0, 0) is the top-left corner, x is the column and y is the row.
  • An ARGB pixel is one int with alpha, red, green and blue in 8 bits each; unpack with shifts and & 0xFF, pack with shifts and |.
  • ImageIO.read and ImageIO.write handle PNG, JPEG, GIF, BMP and more; check read for null and write for false (JPEG and BMP need TYPE_INT_RGB).
  • getRGB(x, y) and setRGB(x, y, argb) read and write one pixel; use the bulk versions for large images.
  • Grayscale weights the channels (0.299, 0.587, 0.114), negative is 255 - c, sepia mixes the channels with a matrix and needs clamping, and a mirror maps x to width - 1 - x.
  • Always write filter results into a new image so the original stays available; recognition tasks such as face detection need a library like OpenCV.

Next: Scanner Deep Dive, where you take input from the console and from files.