Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
Pixel images: reading and writing PNG, JPEG, GIF, BMP and TIFF with ImageIO, readers, writers, multi-image files and JPEG quality, the anatomy of BufferedImage with rasters and color models, pixel access, and filtering with convolution, lookup, rescale, color conversion and affine transforms.
kvi5hnuCode Sprout team member19 min readOn this page
Shapes, strokes and paints describe pictures mathematically: that is vector graphics. Photos, screenshots and scanned documents are grids of colored pixels: raster images. Java handles them with three pieces: the javax.imageio package reads and writes image files; java.awt.image.BufferedImage holds the pixels in memory; and image operations (BufferedImageOp) transform whole images, for blurring, sharpening, color changes or rotation.
Reading and writing images
For everyday use, the static methods of ImageIO are all you need:
BufferedImage image = ImageIO.read(Path.of("photo.jpg").toFile()); // or an InputStream or URL
boolean ok = ImageIO.write(image, "png", Path.of("photo.png").toFile());
read picks a reader by looking at the content of the file: each format starts with recognizable "magic" bytes (PNG files begin with \x89PNG, JPEG files with FF D8). If no reader recognizes the data, read returns null rather than throwing, so check the result. It throws an IOException when a reader accepted the file but failed to decode it, for example because it is truncated.
write takes a format name such as "png", "jpeg" or "gif". It returns false when no writer can handle the format, or this particular image: JPEG has no transparency, and current JDKs refuse to write an image with an alpha channel as JPEG, so write returns false and creates nothing. Draw such an image onto an opaque TYPE_INT_RGB image first.
The JDK ships readers and writers for PNG, JPEG, GIF, BMP, WBMP and TIFF (TIFF since Java 9, JEP 262). Modern web formats such as WebP, AVIF and HEIC are not included. ImageIO is a plugin framework, though: libraries such as TwelveMonkeys register additional readers through the service loader (META-INF/services/javax.imageio.spi.ImageReaderSpi), and once their JAR is on the class path, ImageIO.read handles the new formats too. In an application server or plugin system where JARs appear later, ImageIO.scanForPlugins() repeats the search.
Format choice in brief: PNG is lossless and supports transparency, the default for screenshots, diagrams and UI graphics. JPEG is lossy and much smaller for photos, but damages sharp edges and text. GIF is limited to 256 colors per frame but supports animation. TIFF is common in scanning and printing and can hold many pages. BMP is uncompressed.
By default, ImageIO buffers stream data in temporary files when it needs random access. ImageIO.setUseCache(false) keeps the buffer in memory, which is faster and avoids problems on servers without a writable temp directory.
Readers and writers
The static methods hide two objects that you need for anything beyond the basics: an ImageReader and an ImageWriter. ImageIO finds them by format name, file suffix or MIME type:
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
Iterator<ImageReader> bySuffix = ImageIO.getImageReadersBySuffix("jpg");
Iterator<ImageWriter> byMime = ImageIO.getImageWritersByMIMEType("image/png");
Each returns an iterator, because several plugins may handle the same format. The service provider of a reader describes it: reader.getOriginatingProvider() returns an ImageReaderSpi with getVendorName, getVersion, getFormatNames, getFileSuffixes and getMIMETypes.
ImageIO can also list everything that is installed: getReaderFormatNames, getWriterFormatNames, getReaderFileSuffixes, getWriterFileSuffixes and the MIME type variants. The suffix lists are handy for a file chooser filter:
chooser.setFileFilter(new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes()));
The format name lists contain every alias of every format (jpg, JPG, jpeg, JPEG, ...), which is useless in a menu. The listing below builds a list with one name per writer by asking each writer for its own names and keeping the first one.
To use a reader directly, give it an ImageInputStream, which ImageIO creates from a file, a stream or a RandomAccessFile:
try (ImageInputStream in = ImageIO.createImageInputStream(file)) {
ImageReader reader = ImageIO.getImageReaders(in).next(); // detects the format from the content
reader.setInput(in);
int width = reader.getWidth(0), height = reader.getHeight(0);
BufferedImage image = reader.read(0);
reader.dispose();
}
getWidth and getHeight read only the header, so you can check the size of a huge image before decoding it, for example to reject a 50,000 by 50,000 pixel upload that would need 10 GB of memory. Some formats also contain small preview images: getNumThumbnails(imageIndex) and readThumbnail(imageIndex, thumbnailIndex) retrieve them. Readers and writers hold native resources, so call dispose() when you are done.
Files with several images
Animated GIFs and multi-page TIFFs contain several images. ImageIO.read returns only the first. Read the others by index through a reader:
reader.setInput(in); // random access allowed
int count = reader.getNumImages(true); // may have to scan the whole file
for (int i = 0; i < count; i++) frames.add(reader.read(i));
The second argument of setInput(input, seekForwardOnly) matters for streams. With true, the reader may not go back, so it does not need to buffer: efficient, but getNumImages(true) then throws IllegalStateException, because counting would require reading ahead and coming back. In that mode, read with increasing indexes until read throws IndexOutOfBoundsException. getNumImages(false) never searches; it returns -1 if the header does not state the count, as is the case for GIF.
Writing several images uses a sequence:
ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next();
try (ImageOutputStream out = ImageIO.createImageOutputStream(file)) {
writer.setOutput(out);
if (writer.canWriteSequence()) {
writer.prepareWriteSequence(null);
for (BufferedImage frame : frames) writer.writeToSequence(new IIOImage(frame, null, null), null);
writer.endWriteSequence();
}
}
An IIOImage bundles an image with optional thumbnails and metadata. ImageWriter also has canInsertImage and writeInsert for inserting an image at an index into an existing file, but the GIF writer does not support insertion (the demo shows canInsertImage(1) is false), so sequences are the way to write animated GIFs. Animation details, such as the delay between frames and looping, are stored in the GIF metadata and set through IIOMetadata (the GraphicControlExtension node's delayTime, in hundredths of a second).
Write parameters
The last argument of write and writeToSequence is an ImageWriteParam with format-specific settings. The most common is JPEG quality:
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.85f); // 0 (smallest) to 1 (best)
writer.write(null, new IIOImage(image, null, null), param);
Similar parameters select a TIFF compression type (setCompressionType("LZW"), "Deflate", "JPEG", ...) or progressive JPEG encoding. Readers have an ImageReadParam too; its setSourceRegion and setSourceSubsampling decode only a part or a reduced version of a big image, which saves memory for previews.
One pitfall with photos: cameras store the orientation of the picture in EXIF metadata instead of rotating the pixels. ImageIO.read ignores that tag, so portrait photos may appear sideways. Applications that show user photos have to read the orientation from the metadata (or use a library) and rotate accordingly.
Inside a BufferedImage

BufferedImage is the in-memory image class of Java 2D. You create one with a size and a type:
var image = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics(); // draw on it with everything from the last two articles
...
g.dispose();
The type determines how pixels are stored. The most important ones:
| Type | Storage |
|---|---|
TYPE_INT_RGB | one int per pixel, 8 bits each of red, green and blue |
TYPE_INT_ARGB | one int per pixel with alpha: the natural choice for drawing with transparency |
TYPE_INT_ARGB_PRE | like INT_ARGB, but colors are stored premultiplied by alpha, which makes compositing faster |
TYPE_3BYTE_BGR, TYPE_4BYTE_ABGR | three or four bytes per pixel: the layout JPEG and PNG readers often produce |
TYPE_USHORT_565_RGB | 16 bits per pixel, 5 for red, 6 for green, 5 for blue |
TYPE_BYTE_GRAY, TYPE_USHORT_GRAY | 8 or 16 bits of gray |
TYPE_BYTE_BINARY | 1, 2 or 4 bits per pixel, black and white by default |
TYPE_BYTE_INDEXED | one byte per pixel, an index into a palette of 256 colors (GIF) |
Images loaded by ImageIO may also be TYPE_CUSTOM, a layout without a constant, such as 16-bit-per-channel PNGs.
Internally, a BufferedImage consists of two parts:
- A
WritableRasterholds the pixel data. It contains aDataBuffer, the actual arrays (int[],byte[],short[]), and aSampleModel, which knows how to find the samples of a pixel in those arrays: how many bands (channels) there are and where each lies. - A
ColorModelinterprets samples as colors: which color space (sRGB, linear gray, ...), whether there is alpha, whether it is premultiplied, or which palette maps indexes to colors.
Accessing pixels
There are three levels of pixel access, from convenient to precise.
getRGB and setRGB on BufferedImage work with colors packed into an int as 0xAARRGGBB, in sRGB, whatever the image type. The image converts as needed. Variants take a rectangle and an int[]:
int argb = image.getRGB(x, y);
int red = (argb >> 16) & 0xFF;
image.setRGB(x, y, 0xFF336699);
int[] row = image.getRGB(0, y, width, 1, null, 0, width);
This is the right choice for most code. Its cost is a conversion for each pixel, which is cheap for INT_RGB and INT_ARGB but adds up for other types.
getPixel and setPixel on the raster read and write raw samples, one per band, in an int[], float[] or double[]:
WritableRaster raster = image.getRaster();
int[] samples = raster.getPixel(x, y, (int[]) null);
raster.setPixel(x, y, new int[] {255, 0, 0, 255}); // R, G, B, A for TYPE_INT_ARGB
raster.setSample(x, y, band, value); // a single band
The meaning depends entirely on the type. The demo stores the color (200, 100, 50) with alpha 128 into images of different types and reads back the samples: INT_ARGB gives the four values, INT_ARGB_PRE gives (100, 50, 25, 128) because colors are premultiplied, USHORT_565_RGB gives (24, 25, 6), a 5-6-5 bit approximation, and BYTE_GRAY gives 55. Note that the float[] and double[] variants still use the sample range (0 to 255 for 8-bit bands), not 0.0 to 1.0. getPixels and setPixels move whole rectangles, sample after sample in one flat array.
getDataElements and setDataElements move pixels in the type's own native format, an array whose type and length depend on the image (int[1] for INT_ARGB, byte[3] for 3BYTE_BGR). You do not interpret these arrays yourself; the color model converts between them and ARGB:
ColorModel model = image.getColorModel();
Object data = model.getDataElements(Color.RED.getRGB(), null); // ARGB -> native
raster.setDataElements(x, y, data);
Color c = new Color(model.getRGB(raster.getDataElements(x, y, null)), true);
Converting a color once and then copying the native data into many pixels is fast and works for any image type. The demo draws a Mandelbrot set this way, and the same code produces a correct result for INT_ARGB and BYTE_GRAY images.
Two type subtleties appear in the demo. TYPE_BYTE_GRAY uses a linear gray color space, not sRGB: the gray value 55 for (200, 100, 50) is the linear luminance, which corresponds to the sRGB gray 0x80 reported by getRGB. And storing a color in a type with fewer bits (565, gray, binary) loses information that does not come back.
For maximum speed, you can get the array behind the raster: ((DataBufferInt) raster.getDataBuffer()).getData() for the INT types. Reads and writes are then plain array accesses. The cost: Java 2D can no longer cache the image in video memory once its array has escaped, so drawing that image to the screen becomes slower. Use direct access for heavy processing, not for images you redraw constantly.
Computing an image
The Mandelbrot set is a classic example of computing pixels. For each point (a, b) of the plane, start with (x, y) = (0, 0) and repeat
x' = x² - y² + a
y' = 2xy + b
(squaring the complex number x + iy and adding a + ib). If the distance from the origin ever exceeds 2, the sequence escapes to infinity; points whose sequence stays bounded after many iterations belong to the set and are colored:
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
double a = xMin + i * (xMax - xMin) / width;
double b = yMin + j * (yMax - yMin) / height;
if (bounded(a, b)) raster.setDataElements(i, j, colorData);
}
The demo prints a small version as characters.
Drawing images
To show a BufferedImage, draw it with a Graphics object or wrap it in an ImageIcon for a JLabel:
g.drawImage(image, x, y, null); // at its natural size
g.drawImage(image, x, y, width, height, null); // scaled
g2.drawImage(image, op, x, y); // filtered with a BufferedImageOp while drawing
g2.drawImage(image, transform, null); // through an AffineTransform
The last parameter of the java.awt.Image methods is an ImageObserver, a remnant of the asynchronous image loading of Java 1.0 (Toolkit.getImage still loads images in the background and calls the observer with progress). Images from ImageIO are complete, so pass null. When scaling, the KEY_INTERPOLATION rendering hint selects nearest-neighbor, bilinear or bicubic sampling. Avoid the old Image.getScaledInstance, which is slow and returns a java.awt.Image that is not a BufferedImage.
Since Java 9, MultiResolutionImage (with the implementation BaseMultiResolutionImage) bundles several versions of an image, such as a 16, 32 and 64 pixel icon, and Java 2D picks the one that fits the display's scale factor, so icons stay sharp on HiDPI screens.
Image filters
Instead of manipulating pixels by hand, use the operations in java.awt.image. Each implements the BufferedImageOp interface, whose filter method transforms a source image into a destination image:
BufferedImageOp op = ...;
BufferedImage result = op.filter(source, null); // null: the op creates a suitable destination
op.filter(source, destination); // or supply your own
With null, the operation chooses the destination type through createCompatibleDestImage, and that choice can surprise: the demo shows that an AffineTransformOp with bilinear interpolation turns a gray image into an INT_ARGB image, because interpolated pixels can need alpha at the edges. Supply a destination when you need a specific type. ConvolveOp and AffineTransformOp cannot work in place, with the same image as source and destination (they throw IllegalArgumentException); RescaleOp, LookupOp and ColorConvertOp can. The related RasterOp interface performs the same operations on rasters, without color models.
Five operations are provided.
RescaleOp
RescaleOp computes a · sample + b for every color sample, clamping to the valid range. A factor above 1 increases contrast, a positive offset brightens:
var brighten = new RescaleOp(1.1f, 20f, null);
var perBand = new RescaleOp(new float[] {1f, 1f, 0.5f}, new float[] {0, 0, 0}, null); // less blue
With a single factor and offset, alpha is left alone. With arrays, you supply one entry per color band (alpha unchanged) or one per band including alpha.
LookupOp
LookupOp replaces each sample with a value from a table, which can express any per-channel mapping: negatives, gamma correction, posterization or thresholds.
byte[] negative = new byte[256];
for (int i = 0; i < 256; i++) negative[i] = (byte) (255 - i);
var invert = new LookupOp(new ByteLookupTable(0, negative), null);
ByteLookupTable and ShortLookupTable take an offset (subtracted from each sample before the lookup) and either one table for all color bands or one table per band. Old JDK versions had a bug that made a ByteLookupTable fail on INT images, which is why older code uses ShortLookupTable instead; current JDKs handle both. Neither LookupOp nor RescaleOp works on indexed images, because their samples are palette indexes, not colors: convert such images to an RGB type first, as the listing does.
ColorConvertOp
ColorConvertOp converts between color spaces. The common use is turning a color image gray:
var toGray = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage gray = toGray.filter(color, null);
The conversion uses the luminance of each color, so pure green comes out much brighter than pure red, and blue very dark (183, 57 and 15 in the demo), matching how bright the colors look to people. ColorConvertOp also converts between ICC color profiles, for example from a camera's Adobe RGB to sRGB, through ICC_ColorSpace and ICC_Profile.
ConvolveOp
A convolution replaces each pixel with a weighted sum of itself and its neighbors. The weights form a small matrix, the kernel:
float[] blur = {
1/9f, 1/9f, 1/9f,
1/9f, 1/9f, 1/9f,
1/9f, 1/9f, 1/9f};
var op = new ConvolveOp(new Kernel(3, 3, blur));
Different kernels have very different effects:
- Blur: equal weights averaging the neighborhood (a box blur), or weights that fall off from the center (a Gaussian blur). Larger kernels blur more.
- Sharpen: 5 at the center, -1 at the four direct neighbors. The weights sum to 1, so flat areas stay the same while differences are amplified.
- Edge detection: 4 at the center, -1 at the neighbors. The weights sum to 0, so flat areas become black and only changes remain, as the demo shows for a bright square.
Pixels at the border do not have all neighbors. The edge condition decides what happens there: EDGE_ZERO_FILL (the default) sets the border pixels of the destination to zero, EDGE_NO_OP copies them unchanged from the source. The demo prints both.
AffineTransformOp
AffineTransformOp applies an affine transform (from the previous article) to the pixels, for scaling, rotating, mirroring or shearing an image:
var rotate = AffineTransform.getRotateInstance(Math.toRadians(15), w / 2.0, h / 2.0);
var op = new AffineTransformOp(rotate, AffineTransformOp.TYPE_BICUBIC);
Transformed pixel positions rarely fall exactly on the destination grid, so the op needs an interpolation type: TYPE_NEAREST_NEIGHBOR (copy the closest source pixel: fast, blocky, keeps exact colors), TYPE_BILINEAR (blend the four nearest pixels) or TYPE_BICUBIC (use 16 pixels: smoothest, slowest). The demo scales a row of pixels both ways. You can also pass RenderingHints instead of a type.
The op places the image wherever the transform sends it, and coordinates that end up negative are cut off. getBounds2D(source) tells where the result lands: for a 90-degree rotation around the origin, at x from -7 to 0, entirely outside the destination. Fix this by appending a translation that moves the bounds to the origin and making the destination as large as the bounds, as the listing does.
An image workbench
This program opens an image file in any supported format, shows all its frames (try an animated GIF), applies filters from a menu, and saves the result in any writer format, writing a sequence when the format supports several images.
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import javax.imageio.*;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public final class ImageWorkbench extends JFrame {
private static final long serialVersionUID = 1L;
private transient List<BufferedImage> images = List.of();
private final JPanel strip = new JPanel(new FlowLayout(FlowLayout.LEFT));
public ImageWorkbench() {
super("Image Workbench");
var file = new JMenu("File");
file.add(item("Open...", this::open));
var save = new JMenu("Save as");
for (String format : preferredWriterFormats()) save.add(item(format, () -> save(format)));
file.add(save);
var edit = new JMenu("Filter");
edit.add(item("Blur", () -> convolve(3, box(9))));
edit.add(item("Sharpen", () -> convolve(3, new float[] {0, -1, 0, -1, 5, -1, 0, -1, 0})));
edit.add(item("Edge detect", () -> convolve(3, new float[] {0, -1, 0, -1, 4, -1, 0, -1, 0})));
edit.add(item("Brighten", () -> apply(new RescaleOp(1.1f, 20f, null))));
edit.add(item("Negative", () -> {
byte[] negative = new byte[256];
for (int i = 0; i < 256; i++) negative[i] = (byte) (255 - i);
apply(new LookupOp(new ByteLookupTable(0, negative), null));
}));
edit.add(item("Grayscale", () -> apply(new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null))));
edit.add(item("Rotate 15 degrees", () -> rotate(15)));
var bar = new JMenuBar();
bar.add(file);
bar.add(edit);
setJMenuBar(bar);
add(new JScrollPane(strip));
setSize(600, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private static JMenuItem item(String label, Runnable action) {
var item = new JMenuItem(label);
item.addActionListener(_ -> action.run());
return item;
}
private static float[] box(int n) {
var k = new float[n];
Arrays.fill(k, 1f / n);
return k;
}
/** One name per writer, upper case, e.g. BMP, GIF, JPEG, PNG, TIFF, WBMP. */
static SortedSet<String> preferredWriterFormats() {
var result = new TreeSet<String>();
var remaining = new HashSet<>(Arrays.asList(ImageIO.getWriterFormatNames()));
while (!remaining.isEmpty()) {
String name = remaining.iterator().next();
String[] aliases = ImageIO.getImageWritersByFormatName(name).next().getOriginatingProvider().getFormatNames();
result.add(aliases[0].toUpperCase(Locale.ROOT));
remaining.removeAll(Arrays.asList(aliases));
}
return result;
}
private void open() {
var chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes()));
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
File f = chooser.getSelectedFile();
try (ImageInputStream in = ImageIO.createImageInputStream(f)) {
Iterator<ImageReader> readers = in == null ? Collections.emptyIterator() : ImageIO.getImageReaders(in);
if (!readers.hasNext()) {
JOptionPane.showMessageDialog(this, "No reader for " + f.getName());
return;
}
ImageReader reader = readers.next();
reader.setInput(in);
int count = reader.getNumImages(true); // every frame of an animated GIF or TIFF
var loaded = new ArrayList<BufferedImage>();
for (int i = 0; i < count; i++) loaded.add(toRgb(reader.read(i)));
reader.dispose();
show(loaded);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Cannot read", JOptionPane.ERROR_MESSAGE);
}
}
/** Filters work best on a known, non-indexed type; GIF frames, for example, are indexed. */
private static BufferedImage toRgb(BufferedImage image) {
var copy = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = copy.createGraphics();
g.setColor(Color.WHITE); // transparent areas become white
g.fillRect(0, 0, copy.getWidth(), copy.getHeight());
g.drawImage(image, 0, 0, null);
g.dispose();
return copy;
}
private void save(String format) {
if (images.isEmpty()) return;
ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
var chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter(format + " files",
writer.getOriginatingProvider().getFileSuffixes()));
if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
try (ImageOutputStream out = ImageIO.createImageOutputStream(chooser.getSelectedFile())) {
writer.setOutput(out);
if (images.size() > 1 && writer.canWriteSequence()) {
writer.prepareWriteSequence(null);
for (BufferedImage image : images) writer.writeToSequence(new IIOImage(image, null, null), null);
writer.endWriteSequence();
} else {
writer.write(images.get(0)); // single-image formats keep the first one
}
} catch (IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Cannot write", JOptionPane.ERROR_MESSAGE);
} finally {
writer.dispose();
}
}
private void convolve(int size, float[] kernel) {
apply(new ConvolveOp(new Kernel(size, size, kernel), ConvolveOp.EDGE_NO_OP, null));
}
private void rotate(double degrees) {
var result = new ArrayList<BufferedImage>();
for (BufferedImage image : images) {
var t = AffineTransform.getRotateInstance(Math.toRadians(degrees), image.getWidth() / 2.0, image.getHeight() / 2.0);
// shift so that the rotated image starts at (0, 0) instead of being cut off
Rectangle2D bounds = new AffineTransformOp(t, null).getBounds2D(image);
t.preConcatenate(AffineTransform.getTranslateInstance(-bounds.getX(), -bounds.getY()));
var dest = new BufferedImage((int) Math.ceil(bounds.getWidth()), (int) Math.ceil(bounds.getHeight()),
BufferedImage.TYPE_INT_RGB);
result.add(new AffineTransformOp(t, AffineTransformOp.TYPE_BICUBIC).filter(image, dest));
}
show(result);
}
private void apply(BufferedImageOp op) {
var result = new ArrayList<BufferedImage>();
for (BufferedImage image : images) {
// ConvolveOp cannot work in place; an explicit destination keeps the type
var dest = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
result.add(op.filter(image, dest));
}
show(result);
}
private void show(List<BufferedImage> newImages) {
images = List.copyOf(newImages);
strip.removeAll();
for (BufferedImage image : images) strip.add(new JLabel(new ImageIcon(image)));
strip.revalidate();
strip.repaint();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ImageWorkbench().setVisible(true));
}
}
The reader is chosen from the file's content, not its name, so a PNG renamed to .jpg still opens. Every frame is converted to TYPE_INT_RGB on loading, which makes all filters applicable (GIF frames are indexed) and gives each operation a predictable destination type. Saving a multi-frame image as PNG or BMP keeps only the first frame, because those writers cannot write sequences.
The program
The demo writes and reads image files in a temporary directory, which it deletes at the end, and then works on small images in memory, printing their pixels as characters or as numbers.
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Locale;
import java.util.TreeSet;
import javax.imageio.*;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
public class Solution {
public static void main(String[] args) throws IOException {
System.setProperty("java.awt.headless", "true");
ImageIO.setUseCache(false); // buffer streams in memory, not in temp files
formats();
Path dir = Files.createTempDirectory("images");
try {
readWrite(dir);
multipleImages(dir);
} finally {
try (var files = Files.list(dir)) {
for (Path p : files.toList()) Files.delete(p);
}
Files.delete(dir);
}
pixels();
mandelbrot();
filters();
}
static void formats() {
System.out.println("== Formats supported by ImageIO ==");
System.out.println("readers: " + upper(ImageIO.getReaderFormatNames()));
System.out.println("writers: " + upper(ImageIO.getWriterFormatNames()));
System.out.println("reader MIME types: " + new TreeSet<>(Arrays.asList(ImageIO.getReaderMIMETypes())));
ImageReader reader = ImageIO.getImageReadersBySuffix("jpg").next();
var spi = reader.getOriginatingProvider();
System.out.println("reader for .jpg: formats " + Arrays.toString(spi.getFormatNames())
+ ", suffixes " + Arrays.toString(spi.getFileSuffixes()));
System.out.println("readers for WebP: " + ImageIO.getImageReadersByFormatName("webp").hasNext());
}
static TreeSet<String> upper(String[] names) {
var set = new TreeSet<String>();
for (String n : names) set.add(n.toUpperCase(Locale.ROOT));
return set;
}
static BufferedImage testPicture() {
var image = new BufferedImage(64, 48, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setPaint(new GradientPaint(0, 0, Color.ORANGE, 64, 48, Color.BLUE));
g.fillRect(0, 0, 64, 48);
g.setColor(Color.WHITE);
g.fillOval(16, 8, 32, 32);
g.dispose();
return image;
}
static boolean samePixels(BufferedImage a, BufferedImage b) {
for (int y = 0; y < a.getHeight(); y++)
for (int x = 0; x < a.getWidth(); x++)
if ((a.getRGB(x, y) & 0xFFFFFF) != (b.getRGB(x, y) & 0xFFFFFF)) return false;
return true;
}
static void readWrite(Path dir) throws IOException {
System.out.println();
System.out.println("== Writing and reading files ==");
BufferedImage picture = testPicture();
var colors = new java.util.HashSet<Integer>();
for (int y = 0; y < picture.getHeight(); y++)
for (int x = 0; x < picture.getWidth(); x++) colors.add(picture.getRGB(x, y));
System.out.println("test picture: 64x48, " + colors.size() + " distinct colors");
for (String format : new String[] {"png", "bmp", "tiff", "gif", "jpg"}) {
Path file = dir.resolve("picture." + format);
boolean written = ImageIO.write(picture, format, file.toFile());
BufferedImage back = ImageIO.read(file.toFile());
System.out.printf(" %-4s written %s, read back %dx%d, identical pixels: %s%n", format, written,
back.getWidth(), back.getHeight(), samePixels(picture, back));
}
Path text = dir.resolve("notes.txt");
Files.writeString(text, "not an image");
System.out.println("ImageIO.read of a text file returns " + ImageIO.read(text.toFile()));
var translucent = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
System.out.println("ARGB image as JPEG: write returns "
+ ImageIO.write(translucent, "jpg", new ByteArrayOutputStream()) + " (JPEG has no alpha)");
// the image size without decoding the pixels
try (ImageInputStream in = ImageIO.createImageInputStream(dir.resolve("picture.png").toFile())) {
ImageReader reader = ImageIO.getImageReaders(in).next();
reader.setInput(in, true);
System.out.println("size from the PNG header: " + reader.getWidth(0) + "x" + reader.getHeight(0)
+ ", format " + reader.getFormatName());
reader.dispose();
}
// JPEG quality
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
int[] sizes = new int[2];
float[] qualities = {0.2f, 0.95f};
for (int i = 0; i < 2; i++) {
var bytes = new ByteArrayOutputStream();
try (ImageOutputStream out = ImageIO.createImageOutputStream(bytes)) {
writer.setOutput(out);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(qualities[i]);
writer.write(null, new IIOImage(picture, null, null), param);
}
sizes[i] = bytes.size();
}
writer.dispose();
System.out.println("JPEG at quality 0.2 is smaller than at 0.95: " + (sizes[0] < sizes[1]));
}
static void multipleImages(Path dir) throws IOException {
System.out.println();
System.out.println("== Files with several images ==");
BufferedImage[] frames = new BufferedImage[3];
for (int i = 0; i < frames.length; i++) {
frames[i] = new BufferedImage(20, 10, BufferedImage.TYPE_INT_RGB);
Graphics2D g = frames[i].createGraphics();
g.setColor(Color.WHITE);
g.fillRect(i * 6, 2, 6, 6); // a square moving to the right
g.dispose();
}
for (String format : new String[] {"gif", "tiff"}) {
Path file = dir.resolve("frames." + format);
ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
try (ImageOutputStream out = ImageIO.createImageOutputStream(file.toFile())) {
writer.setOutput(out);
System.out.print(" " + format + ": canWriteSequence " + writer.canWriteSequence());
writer.prepareWriteSequence(null);
for (BufferedImage frame : frames) writer.writeToSequence(new IIOImage(frame, null, null), null);
writer.endWriteSequence();
}
writer.dispose();
try (ImageInputStream in = ImageIO.createImageInputStream(file.toFile())) {
ImageReader reader = ImageIO.getImageReaders(in).next();
reader.setInput(in); // random access: may search
int count = reader.getNumImages(true);
var sb = new StringBuilder();
for (int i = 0; i < count; i++) {
BufferedImage frame = reader.read(i);
int x = 0;
while ((frame.getRGB(x, 5) & 0xFFFFFF) == 0) x++;
sb.append(" ").append(x);
}
System.out.println(", read back " + count + " images, square starts at x =" + sb
+ ", ImageIO.read gets only the first");
reader.dispose();
}
}
ImageWriter gif = ImageIO.getImageWritersByFormatName("gif").next();
gif.setOutput(ImageIO.createImageOutputStream(new ByteArrayOutputStream()));
System.out.println("GIF writer canInsertImage(1): " + gif.canInsertImage(1) + " (use sequences instead)");
gif.dispose();
}
static void pixels() {
System.out.println();
System.out.println("== One color, stored by different image types ==");
var color = new Color(200, 100, 50, 128);
int[] types = {BufferedImage.TYPE_INT_ARGB, BufferedImage.TYPE_INT_ARGB_PRE, BufferedImage.TYPE_INT_RGB,
BufferedImage.TYPE_3BYTE_BGR, BufferedImage.TYPE_USHORT_565_RGB, BufferedImage.TYPE_BYTE_GRAY,
BufferedImage.TYPE_BYTE_BINARY};
String[] names = {"INT_ARGB", "INT_ARGB_PRE", "INT_RGB", "3BYTE_BGR", "USHORT_565_RGB", "BYTE_GRAY", "BYTE_BINARY"};
System.out.printf(" %-15s %-6s %-20s %-16s %s%n", "type", "bands", "samples (getPixel)", "data elements", "back to ARGB");
for (int i = 0; i < types.length; i++) {
var image = new BufferedImage(1, 1, types[i]);
WritableRaster raster = image.getRaster();
ColorModel model = image.getColorModel();
Object data = model.getDataElements(color.getRGB(), null); // color -> type-specific data
raster.setDataElements(0, 0, data);
int[] samples = raster.getPixel(0, 0, (int[]) null);
Object elements = raster.getDataElements(0, 0, null);
String kind = elements.getClass().getComponentType() + "[" + java.lang.reflect.Array.getLength(elements) + "]";
System.out.printf(" %-15s %-6d %-20s %-16s %08X%n", names[i], raster.getNumBands(),
Arrays.toString(samples), kind, model.getRGB(elements));
}
System.out.println("(original color: " + String.format("%08X", color.getRGB()) + ")");
var image = new BufferedImage(4, 1, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, 0x336699); // convenience for single pixels
int[] row = {0xFF0000, 0x00FF00, 0x0000FF};
image.setRGB(1, 0, 3, 1, row, 0, 3); // a block of pixels
int[] direct = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
System.out.print("setRGB, then the int[] behind the raster:");
for (int v : direct) System.out.printf(" %06X", v);
System.out.println();
}
static void mandelbrot() {
System.out.println();
System.out.println("== A Mandelbrot set computed pixel by pixel ==");
int width = 60, height = 21;
for (int type : new int[] {BufferedImage.TYPE_INT_ARGB, BufferedImage.TYPE_BYTE_GRAY}) {
var image = new BufferedImage(width, height, type);
WritableRaster raster = image.getRaster();
ColorModel model = image.getColorModel();
Object inside = model.getDataElements(Color.WHITE.getRGB(), null); // same code for any type
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
double a = -2.2 + i * 3.0 / width;
double b = -1.2 + j * 2.4 / (height - 1);
if (bounded(a, b)) raster.setDataElements(i, j, inside);
}
}
if (type == BufferedImage.TYPE_BYTE_GRAY) {
for (int y = 0; y < height; y++) {
var sb = new StringBuilder(" ");
for (int x = 0; x < width; x++) sb.append((image.getRGB(x, y) & 0xFF) > 0 ? '#' : '.');
System.out.println(sb);
}
} else {
System.out.println("ARGB version: pixel (45, 10) = " + Integer.toHexString(image.getRGB(45, 10))
+ ", pixel (0, 0) = " + Integer.toHexString(image.getRGB(0, 0)) + " (transparent)");
}
}
}
static boolean bounded(double a, double b) {
double x = 0, y = 0;
for (int n = 0; n < 50; n++) {
double xNew = x * x - y * y + a;
y = 2 * x * y + b;
x = xNew;
if (x * x + y * y > 4) return false; // |z| > 2: escapes to infinity
}
return true;
}
/** A 7 x 7 gray test image: a bright 3 x 3 square on a dark background. */
static BufferedImage square() {
var image = new BufferedImage(7, 7, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster r = image.getRaster();
for (int y = 0; y < 7; y++)
for (int x = 0; x < 7; x++)
r.setSample(x, y, 0, x >= 2 && x <= 4 && y >= 2 && y <= 4 ? 180 : 40);
return image;
}
static void show(String title, BufferedImage... images) {
if (!title.isEmpty()) System.out.println(title);
int rows = Arrays.stream(images).mapToInt(BufferedImage::getHeight).max().orElse(0);
for (int y = 0; y < rows; y++) {
var sb = new StringBuilder();
for (BufferedImage image : images) {
sb.append(" ");
for (int x = 0; x < image.getWidth(); x++)
sb.append(y < image.getHeight() ? "%4d".formatted(image.getRaster().getSample(x, y, 0)) : " ");
}
System.out.println(sb.toString().stripTrailing());
}
}
static void filters() {
System.out.println();
System.out.println("== Image filters (BufferedImageOp) on a gray test image ==");
BufferedImage src = square();
show("source, and RescaleOp(1.1, 20): 1.1 * v + 20, clamped", src, new RescaleOp(1.1f, 20f, null).filter(src, null));
byte[] negative = new byte[256];
for (int i = 0; i < 256; i++) negative[i] = (byte) (255 - i);
BufferedImage neg = new LookupOp(new ByteLookupTable(0, negative), null).filter(src, null);
float[] blur = new float[9];
Arrays.fill(blur, 1f / 9);
show("LookupOp negative, and 3 x 3 blur (ConvolveOp, edges zero-filled)",
neg, new ConvolveOp(new Kernel(3, 3, blur)).filter(src, null));
float[] edge = {0, -1, 0, -1, 4, -1, 0, -1, 0};
show("edge detection with EDGE_ZERO_FILL, and with EDGE_NO_OP",
new ConvolveOp(new Kernel(3, 3, edge)).filter(src, null),
new ConvolveOp(new Kernel(3, 3, edge), ConvolveOp.EDGE_NO_OP, null).filter(src, null));
var scale = new AffineTransformOp(AffineTransform.getScaleInstance(1.5, 1), AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
var smooth = new AffineTransformOp(AffineTransform.getScaleInstance(1.5, 1), AffineTransformOp.TYPE_BILINEAR);
BufferedImage nearest = scale.filter(src, null);
BufferedImage automatic = smooth.filter(src, null);
System.out.println("filter(src, null) creates: nearest neighbor -> type " + nearest.getType()
+ " (TYPE_BYTE_GRAY), bilinear -> type " + automatic.getType() + " (TYPE_INT_ARGB)");
BufferedImage bilinear = smooth.filter(src, new BufferedImage(11, 7, BufferedImage.TYPE_BYTE_GRAY));
System.out.println("the 7 x 7 image scaled 1.5 times horizontally to " + nearest.getWidth() + " x "
+ nearest.getHeight() + "; middle row with nearest neighbor, then bilinear into a gray image:");
show("", nearest.getSubimage(0, 3, nearest.getWidth(), 1), bilinear.getSubimage(0, 3, bilinear.getWidth(), 1));
System.out.println("bounds of a 90 degree rotation of the 7 x 7 image: "
+ new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 2), AffineTransformOp.TYPE_BILINEAR)
.getBounds2D(src));
var rgb = new BufferedImage(3, 1, BufferedImage.TYPE_INT_RGB);
rgb.setRGB(0, 0, 0xFF0000);
rgb.setRGB(1, 0, 0x00FF00);
rgb.setRGB(2, 0, 0x0000FF);
var toGray = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage grayImage = toGray.filter(rgb, new BufferedImage(3, 1, BufferedImage.TYPE_BYTE_GRAY));
System.out.println("ColorConvertOp to gray: red, green, blue become "
+ grayImage.getRaster().getSample(0, 0, 0) + ", " + grayImage.getRaster().getSample(1, 0, 0)
+ ", " + grayImage.getRaster().getSample(2, 0, 0) + " (green looks brightest)");
try {
new ConvolveOp(new Kernel(3, 3, blur)).filter(src, src);
} catch (IllegalArgumentException e) {
System.out.println("ConvolveOp in place: " + e.getMessage());
}
}
}
== Formats supported by ImageIO ==
readers: [BMP, GIF, JPEG, JPG, PNG, TIF, TIFF, WBMP]
writers: [BMP, GIF, JPEG, JPG, PNG, TIF, TIFF, WBMP]
reader MIME types: [image/bmp, image/gif, image/jpeg, image/png, image/tiff, image/vnd.wap.wbmp, image/x-png]
reader for .jpg: formats [JPEG, jpeg, JPG, jpg], suffixes [jpg, jpeg]
readers for WebP: false
== Writing and reading files ==
test picture: 64x48, 252 distinct colors
png written true, read back 64x48, identical pixels: true
bmp written true, read back 64x48, identical pixels: true
tiff written true, read back 64x48, identical pixels: true
gif written true, read back 64x48, identical pixels: true
jpg written true, read back 64x48, identical pixels: false
ImageIO.read of a text file returns null
ARGB image as JPEG: write returns false (JPEG has no alpha)
size from the PNG header: 64x48, format png
JPEG at quality 0.2 is smaller than at 0.95: true
== Files with several images ==
gif: canWriteSequence true, read back 3 images, square starts at x = 0 6 12, ImageIO.read gets only the first
tiff: canWriteSequence true, read back 3 images, square starts at x = 0 6 12, ImageIO.read gets only the first
GIF writer canInsertImage(1): false (use sequences instead)
== One color, stored by different image types ==
type bands samples (getPixel) data elements back to ARGB
INT_ARGB 4 [200, 100, 50, 128] int[1] 80C86432
INT_ARGB_PRE 4 [100, 50, 25, 128] int[1] 80C76432
INT_RGB 3 [200, 100, 50] int[1] FFC86432
3BYTE_BGR 3 [200, 100, 50] byte[3] FFC86432
USHORT_565_RGB 3 [24, 25, 6] short[1] FFC56531
BYTE_GRAY 1 [55] byte[1] FF808080
BYTE_BINARY 1 [0] byte[1] FF000000
(original color: 80C86432)
setRGB, then the int[] behind the raster: 336699 FF0000 00FF00 0000FF
== A Mandelbrot set computed pixel by pixel ==
ARGB version: pixel (45, 10) = ffffffff, pixel (0, 0) = 0 (transparent)
............................................................
............................................................
............................................................
.........................................##.................
........................................####................
..................................#..##########.............
.................................#################..........
..............................######################........
.....................#.###....######################........
....................#########.######################........
....##############################################..........
....................#########.######################........
.....................#.###....######################........
..............................######################........
.................................#################..........
..................................#..##########.............
........................................####................
.........................................##.................
............................................................
............................................................
............................................................
== Image filters (BufferedImageOp) on a gray test image ==
source, and RescaleOp(1.1, 20): 1.1 * v + 20, clamped
40 40 40 40 40 40 40 64 64 64 64 64 64 64
40 40 40 40 40 40 40 64 64 64 64 64 64 64
40 40 180 180 180 40 40 64 64 218 218 218 64 64
40 40 180 180 180 40 40 64 64 218 218 218 64 64
40 40 180 180 180 40 40 64 64 218 218 218 64 64
40 40 40 40 40 40 40 64 64 64 64 64 64 64
40 40 40 40 40 40 40 64 64 64 64 64 64 64
LookupOp negative, and 3 x 3 blur (ConvolveOp, edges zero-filled)
215 215 215 215 215 215 215 0 0 0 0 0 0 0
215 215 215 215 215 215 215 0 55 71 86 71 55 0
215 215 75 75 75 215 215 0 71 102 133 102 71 0
215 215 75 75 75 215 215 0 86 133 180 133 86 0
215 215 75 75 75 215 215 0 71 102 133 102 71 0
215 215 215 215 215 215 215 0 55 71 86 71 55 0
215 215 215 215 215 215 215 0 0 0 0 0 0 0
edge detection with EDGE_ZERO_FILL, and with EDGE_NO_OP
0 0 0 0 0 0 0 40 40 40 40 40 40 40
0 0 0 0 0 0 0 40 0 0 0 0 0 40
0 0 255 140 255 0 0 40 0 255 140 255 0 40
0 0 140 0 140 0 0 40 0 140 0 140 0 40
0 0 255 140 255 0 0 40 0 255 140 255 0 40
0 0 0 0 0 0 0 40 0 0 0 0 0 40
0 0 0 0 0 0 0 40 40 40 40 40 40 40
filter(src, null) creates: nearest neighbor -> type 10 (TYPE_BYTE_GRAY), bilinear -> type 2 (TYPE_INT_ARGB)
the 7 x 7 image scaled 1.5 times horizontally to 11 x 7; middle row with nearest neighbor, then bilinear into a gray image:
40 40 40 180 180 180 180 180 40 40 0 40 40 63 157 180 180 180 110 40 40 0
bounds of a 90 degree rotation of the 7 x 7 image: java.awt.geom.Rectangle2D$Float[x=-7.0,y=0.0,w=7.0,h=7.0]
ColorConvertOp to gray: red, green, blue become 57, 183, 15 (green looks brightest)
ConvolveOp in place: src image cannot be the same as the dst image
Points to notice:
- The formats come from the JDK alone; there is no WebP reader without a plugin.
- PNG, BMP, TIFF and GIF stored the 252-color picture exactly (GIF only because it has fewer than 256 colors); JPEG changed pixels even at its default quality.
- Reading a text file returned
null, and writing an ARGB image as JPEG returnedfalse: both fail without an exception. - The GIF and TIFF files each held three frames, with the square moving 6 pixels per frame;
ImageIO.readwould have returned only the first. - The same color looks different in each storage type, and the
565, gray and binary types lost information.getRGBon the gray pixel returned0x80gray although the sample is 55, because the gray color space is linear. setRGBon anINT_RGBimage wrote straight into theint[]of the data buffer.- The blur spread the bright square into its surroundings; edge detection turned the flat areas to 0 and marked the outline, with clamped 255 at the corners.
EDGE_NO_OPkept the border pixels at 40. - The scaled image is 11 pixels wide; its last column lies outside the transformed source, so it stays 0.
Common questions
Which image formats can Java read and write out of the box?
PNG, JPEG, GIF, BMP, WBMP and TIFF, for both reading and writing (ImageIO.getReaderFormatNames() lists them). WebP, HEIF/HEIC and AVIF need plugins such as TwelveMonkeys.
How do I resize an image with good quality?
Draw it into a new BufferedImage with KEY_INTERPOLATION set to VALUE_INTERPOLATION_BICUBIC (or BILINEAR) and KEY_RENDERING to VALUE_RENDER_QUALITY. For large reductions, halve the size in several steps. (Image.getScaledInstance with SCALE_AREA_AVERAGING also works but is slow and doesn't return a BufferedImage, so it has to be drawn into one.)
How do I set JPEG quality?
Get an ImageWriter for "jpeg", create ImageWriteParam, call setCompressionMode(MODE_EXPLICIT) and setCompressionQuality(0.85f), then write through an ImageOutputStream. ImageIO.write uses a default quality.
Why does ImageIO.write return false (and write nothing) for my transparent PNG as JPEG?
JPEG has no alpha channel. Convert first: draw the image onto a TYPE_INT_RGB image filled with white (or another background), then write that.
Why does my photo appear rotated?
Cameras store the orientation in EXIF metadata, which ImageIO doesn't apply. Read the orientation tag (with a metadata library) and rotate the image accordingly.
Why does ImageIO.read return null?
No installed reader recognizes the format. Check the file type, or add a plugin for formats like WebP.
API reference
| Class / method | Purpose |
|---|---|
ImageIO.read(File/InputStream/URL), write(image, format, File/OutputStream), setUseCache | Simple reading and writing. |
getImageReaders(input), getImageReadersByFormatName/BySuffix/ByMIMEType, getImageWritersByFormatName/BySuffix/ByMIMEType | Finding readers and writers. |
getReaderFormatNames, getWriterFormatNames, getReaderFileSuffixes, getWriterFileSuffixes, getReaderMIMETypes, scanForPlugins | Installed formats. |
createImageInputStream, createImageOutputStream | Image streams. |
ImageReader.setInput(in, seekForwardOnly), read(i), getNumImages(allowSearch), getWidth, getHeight, getNumThumbnails, readThumbnail, getOriginatingProvider, dispose | Reading in detail. |
ImageWriter.setOutput, write, canWriteSequence, prepareWriteSequence, writeToSequence, endWriteSequence, canInsertImage, writeInsert, getDefaultWriteParam | Writing in detail. |
IIOImage(image, thumbnails, metadata), ImageWriteParam.setCompressionMode/setCompressionQuality/setCompressionType, ImageReadParam.setSourceRegion | Images with metadata and parameters. |
ImageReaderWriterSpi.getFormatNames/getFileSuffixes/getMIMETypes, getVendorName, getVersion | Plugin descriptions. |
BufferedImage(w, h, type), TYPE_INT_RGB, TYPE_INT_ARGB, TYPE_BYTE_GRAY, TYPE_BYTE_INDEXED, ...; createGraphics, getRGB, setRGB, getRaster, getColorModel, getSubimage | In-memory images. |
Raster.getPixel/getPixels/getSample/getDataElements, WritableRaster.setPixel/setPixels/setSample/setDataElements, getDataBuffer, getNumBands | Raw pixel access. |
ColorModel.getRGB(data), getDataElements(argb, data); Color(argb, hasAlpha), getRGB | Converting between native data and ARGB. |
BufferedImageOp.filter(src, dst), createCompatibleDestImage, getBounds2D | Image operations. |
RescaleOp, LookupOp with ByteLookupTable/ShortLookupTable, ColorConvertOp, ConvolveOp with Kernel and EDGE_ZERO_FILL/EDGE_NO_OP, AffineTransformOp with TYPE_NEAREST_NEIGHBOR/TYPE_BILINEAR/TYPE_BICUBIC | The five filters. |
Graphics.drawImage(...), Graphics2D.drawImage(image, op, x, y), ImageIcon, BaseMultiResolutionImage | Displaying images. |
Summary
ImageIO.readandImageIO.writehandle PNG, JPEG, GIF, BMP, WBMP and TIFF; they signal unsupported input withnullorfalse. Plugins add more formats.ImageReaderandImageWritergive access to image sizes before decoding, multiple images, thumbnails, metadata and compression settings. Write animated GIFs and multi-page TIFFs as sequences.- A
BufferedImagecombines a raster (data buffer and sample model) with a color model. Access pixels withgetRGB/setRGB(ARGB),getPixel/setPixel(raw samples) orgetDataElements/setDataElementswith the color model (native format, works for any type). BufferedImageOps transform whole images:RescaleOpandLookupOpper sample,ColorConvertOpbetween color spaces,ConvolveOpwith a kernel for blurring, sharpening and edge detection, andAffineTransformOpwith interpolation for geometric changes. Supply the destination when its type matters, and never filter in place with a convolution.
Practice Questions
1. A program calls ImageIO.read on an uploaded file and gets a NullPointerException a few lines later. What happened, and how should the code be written?
ImageIO.read returns null when no installed reader recognizes the data, for example for a WebP image or a file that is not an image at all. The code used the result without checking it. Check for null and report an unsupported format; an IOException covers the separate case of a recognized but damaged file. For uploads, also check reader.getWidth(0) and getHeight(0) before decoding to reject images too big for memory.
2. What is the difference between getRGB, getPixel and getDataElements?
BufferedImage.getRGB returns the color as a packed sRGB 0xAARRGGBB int, converting from whatever the image type stores; it is the simplest and type-independent. Raster.getPixel returns the raw samples of each band, whose meaning depends on the image type (premultiplied, 5-6-5 bits, a palette index, linear gray, ...). getDataElements returns the pixel in the type's native format as an opaque array that only the color model interprets; with ColorModel.getDataElements you convert a color once and can then copy it efficiently into any image type.
3. Why does an edge-detection kernel have weights that sum to 0, and a sharpening kernel weights that sum to 1?
The sum of the weights is the factor applied to a completely flat area, where all neighbors equal the center. With a sum of 0 (4 at the center, -1 at four neighbors), flat areas become 0 and only places where the value changes produce a response: the edges. With a sum of 1 (5 and -1s), flat areas keep their value, and the differences to the neighbors are added on top, which makes edges crisper while the overall brightness stays the same. A blur kernel also sums to 1 so the image does not get brighter or darker.
4. A program rotates an image by 30 degrees with an AffineTransformOp around its center, but the corners of the result are cut off. Why, and how is it fixed?
With a null destination, the op creates an image reaching from (0,0) to the far corner of the transformed bounds, so everything at negative coordinates (the top and left corners of the rotated image) is cut off; with a destination the size of the source, the other corners are lost too. Call op.getBounds2D(image) to find where the result lands, add a translation by minus the bounds' x and y to the transform (preConcatenate), and create a destination as large as the bounds.
5. An application writes animated GIFs with writer.write for the first frame and writeInsert for the rest, guarded by canInsertImage. The files show only one frame. Why?
The GIF writer does not support inserting images into a file, so canInsertImage returns false for every index and the loop writes nothing after the first frame. Multiple images must be written as a sequence: check canWriteSequence(), call prepareWriteSequence, then writeToSequence for each frame, and finally endWriteSequence. Frame delays and looping are configured through the GIF image metadata.
Previous: Java 2D Strokes, Paint, Transforms, Clipping and Transparency
Next: Printing in Java: Print Jobs, Multipage Printing and Print Services
Related reading
- Java 2D Strokes, Paint, Transforms, Clipping and Transparency
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Swing Trees: JTree, Tree Models, Nodes and Paths
- Swing Table Cell Renderers and Editors: Custom Rendering and Editing
- Swing Tables: JTable, Table Models, Sorting and Filtering

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.