How do I scale and paint an image in Swing?

Java Image Tutorials

In the previous post, we chose file formats and exported images. In this example, we will display one image at different sizes, keep its aspect ratio, and compare three interpolation methods. Use JDK 25. The program creates a small sample image, so no input file is required.

Paint inside a component

For custom Swing drawing, extend JPanel and override paintComponent(Graphics). Call super.paintComponent(g) first so the panel can paint its background. Then use a copy of the graphics context and dispose of that copy when finished. Keep the graphics context supplied by Swing intact.

Swing calls the painting method when the component needs updating, including after resizing. When your application changes something that affects its appearance, call repaint() to request another paint. Avoid loading files or performing expensive calculations inside the painting method.

Keep the aspect ratio

Suppose an image is 160 × 100 pixels. Its aspect ratio is 1.6. Stretching it to 300 × 300 would distort the image. To fit it inside an available area, calculate one scale factor for both dimensions:

scale = min(availableWidth / imageWidth, availableHeight / imageHeight)
drawWidth = imageWidth * scale
drawHeight = imageHeight * scale

Use floating-point division. Center the result by dividing the remaining space by two. This leaves empty space above and below, or on the left and right. Integer rounding can introduce a small ratio difference of less than a pixel in a dimension.

Choose interpolation

Interpolation determines how Java 2D samples pixels when drawing at a different size.

Hint value What to look for
VALUE_INTERPOLATION_NEAREST_NEIGHBOR Sharp blocks when enlarged; useful for pixel art
VALUE_INTERPOLATION_BILINEAR Smoother transitions; a useful starting point for general images
VALUE_INTERPOLATION_BICUBIC Uses a larger neighborhood; can produce smoother detail but may cost more work

Set these values with RenderingHints.KEY_INTERPOLATION. They are rendering hints; results can vary with the graphics implementation and destination. Shape antialiasing and image interpolation are separate settings. Enabling antialiasing alone does not select the image scaling algorithm.

Complete Java example

Save this file as ScaleImageExample.java.

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ScaleImageExample {
    private static final String[] NAMES = {"Nearest neighbor", "Bilinear", "Bicubic"};
    private static final Object[] HINTS = {
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC
    };

    public static void main(String[] args) throws Exception {
        BufferedImage image = createImage();
        if (args.length == 1 && args[0].equals("--export")) {
            SwingUtilities.invokeAndWait(() -> {
                try {
                    exportPanels(image);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            return;
        }
        if (GraphicsEnvironment.isHeadless()) {
            System.out.println("No display available. Run with --export instead.");
            return;
        }
        SwingUtilities.invokeLater(() -> showWindow(image));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(160, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(8, 8, 144, 84);
            g.setColor(Color.ORANGE);
            g.fillOval(20, 20, 50, 50);
            g.setColor(Color.WHITE);
            g.drawLine(0, 99, 159, 0);
            g.drawString("Java", 90, 60);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static void showWindow(BufferedImage image) {
        JPanel content = new JPanel(new GridLayout(1, 3, 8, 8));
        for (int i = 0; i < HINTS.length; i++) {
            content.add(new ImagePanel(image, NAMES[i], HINTS[i]));
        }
        JFrame frame = new JFrame("Java image scaling");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void exportPanels(BufferedImage image) throws IOException {
        for (int i = 0; i < HINTS.length; i++) {
            ImagePanel panel = new ImagePanel(image, NAMES[i], HINTS[i]);
            panel.setSize(320, 260);
            BufferedImage output = new BufferedImage(320, 260, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = output.createGraphics();
            try {
                panel.paint(g);
            } finally {
                g.dispose();
            }
            File file = new File("scaled-" + i + ".png");
            if (!ImageIO.write(output, "png", file)) {
                throw new IOException("No PNG writer available");
            }
            System.out.println("Saved " + file.getName() + " (320 x 260)");
        }
    }

    private static class ImagePanel extends JPanel {
        private final BufferedImage image;
        private final Object interpolation;

        ImagePanel(BufferedImage image, String title, Object interpolation) {
            this.image = image;
            this.interpolation = interpolation;
            setOpaque(true);
            setBackground(new Color(235, 235, 235));
            setBorder(BorderFactory.createTitledBorder(title));
            setPreferredSize(new Dimension(320, 260));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Insets insets = getInsets();
            int availableWidth = getWidth() - insets.left - insets.right;
            int availableHeight = getHeight() - insets.top - insets.bottom;
            if (availableWidth <= 0 || availableHeight <= 0) {
                return;
            }
            double scale = Math.min(
                    (double) availableWidth / image.getWidth(),
                    (double) availableHeight / image.getHeight());
            int width = Math.max(1, (int) Math.round(image.getWidth() * scale));
            int height = Math.max(1, (int) Math.round(image.getHeight() * scale));
            int x = insets.left + (availableWidth - width) / 2;
            int y = insets.top + (availableHeight - height) / 2;

            Graphics2D copy = (Graphics2D) g.create();
            try {
                copy.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation);
                copy.drawImage(image, x, y, width, height, this);
            } finally {
                copy.dispose();
            }
        }
    }
}

Run the program

Compile and launch on a desktop:

javac --release 25 ScaleImageExample.java
java ScaleImageExample

Scale Image Example

A window titled Java image scaling should contain three labeled panels. Each shows a blue rectangle, orange circle, diagonal line, and text. Resize the window horizontally and vertically. Each image should remain centered and retain its shape. The panel background shows through transparent parts of the source image.

You can also render the panels to PNG files without a display:

java -Djava.awt.headless=true ScaleImageExample --export

Expected console output:

Saved scaled-0.png (320 x 260)
Saved scaled-1.png (320 x 260)
Saved scaled-2.png (320 x 260)

The files are written to the working directory and replaced on later export runs. Open them side by side and zoom in on the diagonal line and circle. File 0 uses nearest neighbor, file 1 uses bilinear interpolation, and file 2 uses bicubic interpolation. Exact font appearance and border dimensions depend on the environment.

How the drawing works

The drawImage(image, x, y, width, height, observer) overload scales the source into the destination rectangle. The original BufferedImage stays 160 × 100 pixels. Display scaling does not resize its stored pixel grid or modify a file.

The panel subtracts its border insets before calculating the available area. This keeps the drawing inside the titled border. Transparent source pixels reveal the panel background, which super.paintComponent(g) paints first.

Passing this supplies the panel as an ImageObserver. A BufferedImage already has its pixel data, so this example does not need to wait for asynchronous image loading.

We create the source before scheduling the UI. Swing component construction and updates happen on the Event Dispatch Thread. The export mode uses that thread too. Its call to panel.paint(g) deliberately renders the complete component, including its border, into an offscreen image. In a normal interactive application, request screen painting with repaint() instead of calling paint() yourself.

For an external file, load it with ImageIO.read() before constructing the UI and check for a null result, as in Week 01. An interactive Open action should use a background worker for file I/O so the UI stays responsive.

This example scales from the original image on every paint. For large images, caching a scaled copy can help, but rebuild the cache when its target size or interpolation changes. Always scale from the original rather than repeatedly resizing a previously resized image. Strong downscaling may need more careful resampling than a single interpolation pass.

Try it yourself

Prevent enlargement by replacing the scale calculation with:

double scale = Math.min(1.0, Math.min(
        (double) availableWidth / image.getWidth(),
        (double) availableHeight / image.getHeight()));

Make the window larger. The image should stay at its original logical drawing size and remain centered. Make it smaller, and the image should shrink to fit. On a display with scaling enabled, logical drawing units do not necessarily correspond one-to-one with physical screen pixels.

Next, load a photograph and compare the interpolation methods when shrinking it. Which setting gives the most useful result for your image?

In the next post, we will use double buffering and animate an object with a Swing timer.

References

How do I choose an image file format in Java?

Java Image Tutorials

In the previous post, we created a transparent image and saved it as PNG. In this example, we will choose formats for different tasks, check the available Image I/O codecs, and export a transparent drawing as PNG and JPEG. The program creates its own image, so you do not need an input file.

Choose a format for your image

A file format describes how an image is stored on disk. A BufferedImage holds decoded pixels in memory. Its type, such as TYPE_INT_ARGB, is separate from the format you use to save those pixels.

Format Compression and transparency Typical use
PNG Lossless; supports full alpha transparency Screenshots, diagrams, icons, and images with text
JPEG Usually lossy; no alpha transparency Photographs where smaller files matter
GIF Lossless compression of indexed colors; up to 256 palette entries per frame and one transparent palette index Small palette graphics and simple animations
BMP Often uncompressed; alpha support varies across variants and software Compatibility with software that specifically requires BMP
TIFF Supports several compression methods; alpha depends on the image layout and reader Scanned documents, publishing, and workflows that need multiple pages or specialized metadata

For a transparent logo, start with PNG. For a photograph, try JPEG and inspect the result. For scans, follow the requirements of the receiving application, which may request TIFF.

GIF compression does not mean an arbitrary full-color image keeps all its colors: converting to a limited palette can change them. GIF also cannot preserve smooth, partially transparent edges. TIFF is a family of capabilities; test the particular compression and image layout required by your workflow.

File size depends on image content, dimensions, and encoder settings. A flat-color diagram can be smaller as PNG than JPEG. Do not assume one format always produces the smallest file.

Check codec support

A reader decodes a file into pixels. A writer encodes pixels into a file. Java 25 supplies standard Image I/O plug-ins for PNG, JPEG, GIF, BMP, TIFF, and WBMP. Additional plug-ins can add formats.

Use ImageIO.getImageReadersByFormatName() and getImageWritersByFormatName() to check registered support. The presence of a writer does not guarantee it accepts every image layout. For example, convert an ARGB image to an opaque RGB image before writing JPEG.

Complete Java example

Save this code as ImageFormatExample.java.

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ImageFormatExample {
    public static void main(String[] args) throws IOException {
        for (String format : new String[]{"png", "jpeg", "gif", "bmp", "tiff", "webp"}) {
            boolean reader = ImageIO.getImageReadersByFormatName(format).hasNext();
            boolean writer = ImageIO.getImageWritersByFormatName(format).hasNext();
            System.out.printf("%s: reader=%s, writer=%s%n", format, reader, writer);
        }

        BufferedImage source = createImage();
        BufferedImage opaque = flatten(source, Color.WHITE);

        Path directory = Path.of("image-formats-output");
        Files.createDirectories(directory);
        saveAndInspect(source, "png", directory.resolve("card.png"));
        saveAndInspect(opaque, "jpeg", directory.resolve("card.jpg"));
        saveAndInspect(opaque, "gif", directory.resolve("card.gif"));
        saveAndInspect(opaque, "bmp", directory.resolve("card.bmp"));
        saveAndInspect(opaque, "tiff", directory.resolve("card.tiff"));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(20, 20, 280, 160);
            g.setColor(new Color(255, 120, 0, 128));
            g.fillOval(0, 60, 100, 100);
            g.setColor(Color.WHITE);
            g.drawString("Java image formats", 110, 105);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static BufferedImage flatten(BufferedImage source, Color background) {
        if (background.getAlpha() != 255) {
            throw new IllegalArgumentException("Background must be opaque");
        }
        BufferedImage result = new BufferedImage(
                source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        try {
            g.setColor(background);
            g.fillRect(0, 0, result.getWidth(), result.getHeight());
            g.drawImage(source, 0, 0, null);
        } finally {
            g.dispose();
        }
        return result;
    }

    private static void saveAndInspect(BufferedImage image, String format, Path path)
            throws IOException {
        if (!ImageIO.write(image, format, path.toFile())) {
            throw new IOException("No suitable writer for " + format);
        }
        BufferedImage loaded = ImageIO.read(path.toFile());
        if (loaded == null) {
            throw new IOException("No reader recognizes " + path);
        }
        System.out.printf("%s: %d x %d, corner alpha=%d%n",
                path.getFileName(), loaded.getWidth(), loaded.getHeight(),
                loaded.getRGB(0, 0) >>> 24);
    }
}

Run the program

Open a terminal in the folder containing the source file:

javac --release 25 ImageFormatExample.java
java -Djava.awt.headless=true ImageFormatExample

The program uses Java 2D without opening a window. It works in a headless environment. It creates the image-formats-output folder in the working directory. Running it again replaces the five output files.

With the standard Java 25 plug-ins and no additional codecs, the expected console output is:

png: reader=true, writer=true
jpeg: reader=true, writer=true
gif: reader=true, writer=true
bmp: reader=true, writer=true
tiff: reader=true, writer=true
webp: reader=false, writer=false
card.png: 320 x 200, corner alpha=0
card.jpg: 320 x 200, corner alpha=255
card.gif: 320 x 200, corner alpha=255
card.bmp: 320 x 200, corner alpha=255
card.tiff: 320 x 200, corner alpha=255

Installed plug-ins can change the codec availability lines. Open the files in an image viewer: PNG keeps a transparent border, while the other exports have a white background. The orange circle is partially transparent in PNG and blended with the background in the other files. JPEG may show artifacts around text and sharp edges. GIF may change colors to fit its palette.

Why flatten the image before writing JPEG?

A new ARGB image starts with transparent pixels. Simply dropping alpha can produce an unwanted background. The flatten() method first paints an opaque background into a TYPE_INT_RGB image, then draws the source over it. The default source-over compositing blends partially transparent pixels with that background.

The JPEG writer receives ordinary RGB pixels. We also use this opaque copy for GIF, BMP, and TIFF so the comparison has a consistent background; this does not mean those formats all have the same transparency capabilities.

The format argument controls encoding: "jpeg" produces JPEG data. The .jpg extension is a useful label for other software, but renaming a PNG file to .jpg does not convert it.

ImageIO.write() returns false when no appropriate writer is found. ImageIO.read() returns null when no registered reader recognizes the data. Both operations can also throw an IOException. Checking these outcomes gives clearer failures than assuming every export succeeded.

The convenience methods use default encoding settings. To control JPEG quality, use an ImageWriter with ImageWriteParam. For animated GIF or multiple-page TIFF output, use the writer’s sequence API where supported; one call to ImageIO.write() is not an animation or multi-page document builder. This example compares pixels and does not preserve source metadata.

What about WebP?

WebP is not one of Java 25’s standard Image I/O formats. A compatible third-party Image I/O provider can add support. Check reading and writing separately: a provider may only implement decoding. After installing a provider according to its documentation, rerun the availability checks. Do not assume an arbitrary WebP library registers an Image I/O writer.

Image I/O discovers service providers on the application class path. ImageIO.scanForPlugins() can rescan it when providers become available after initial discovery. No WebP provider is needed for this tutorial, and the program does not attempt to write WebP.

Try it yourself

Change the flattening background to Color.LIGHT_GRAY, then run the example again. The PNG corner should remain transparent; the other files should show the new background.

Next, print each file’s size using Files.size(path) inside saveAndInspect(). Compare the sizes and inspect the text edges. Repeat with a photograph loaded using ImageIO.read(), keeping the null check. Explain why the smallest format may differ between the drawing and the photograph.

In the next post, we will scale and paint an image in Swing while preserving its aspect ratio.

References

How do I create, load, and display an image in Java?

Java Image Tutorials

In this example, you will draw a blue card in memory, save it as a PNG file, open that file, and show the loaded image in a Swing window. The program creates its own image.

What is a pixel?

A raster image is a grid of pixels. In a BufferedImage, the top-left pixel is at (0, 0). The x coordinate increases to the right, and the y coordinate increases downward.

This example uses BufferedImage.TYPE_INT_ARGB. Each pixel has four values for alpha, red, green, and blue. Alpha controls opacity. A value of 0 means fully transparent, and 255 means fully opaque. The program draws inside the image and leaves a transparent border, which PNG preserves when you save the file.

Java example

Save the following code as JavaImageBasics.java.

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class JavaImageBasics {
    public static void main(String[] args) throws IOException {
        BufferedImage image = createImage();

        File file = new File("java-image.png");
        if (!ImageIO.write(image, "png", file)) {
            throw new IOException("PNG writer is unavailable");
        }

        BufferedImage loadedImage = ImageIO.read(file);
        if (loadedImage == null) {
            throw new IOException("Unrecognized image format: " + file);
        }

        System.out.printf("%s: %d x %d pixels%n",
                file.getName(), loadedImage.getWidth(), loadedImage.getHeight());

        if (!GraphicsEnvironment.isHeadless()) {
            SwingUtilities.invokeLater(() -> showImage(loadedImage));
        }
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics = image.createGraphics();
        try {
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setColor(new Color(33, 99, 200));
            graphics.fillRoundRect(20, 20, 280, 160, 30, 30);
            graphics.setColor(Color.WHITE);
            graphics.drawString("Hello, Java Images!", 100, 105);
        } finally {
            graphics.dispose();
        }

        return image;
    }

    private static void showImage(BufferedImage image) {
        JFrame frame = new JFrame("Java Images");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel(new ImageIcon(image)));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Run the program

Open a terminal in the folder containing the Java file and run these commands.

javac JavaImageBasics.java
java JavaImageBasics

The program writes java-image.png to the working directory and prints the dimensions of the loaded file.

Java Image

java-image.png: 320 x 200 pixels

On a desktop, a Swing window shows the blue card. The transparent border lets the component background show through. In a headless environment, the program still writes and reads the file and prints its dimensions.

How it works

  1. Create. createGraphics() returns a Graphics2D object that draws directly into the BufferedImage. The finally block calls dispose() to release the drawing context.
  2. Save. ImageIO.write() selects an encoder using the format name "png". It returns false if no suitable writer is available.
  3. Load. ImageIO.read() decodes the file into a new BufferedImage. It returns null if no installed reader recognizes the data. An error while opening or reading the file can throw an IOException.
  4. Display. ImageIcon wraps the loaded image, and JLabel displays the icon. SwingUtilities.invokeLater() creates the window on Swing’s Event Dispatch Thread after the file has been read.

Try it yourself

Change the image size to 480 × 240 pixels. Resize the blue rectangle so it still has a 20-pixel margin on all sides. Then print the alpha value for the top-left pixel and for a pixel inside the blue rectangle.

int cornerAlpha = loadedImage.getRGB(0, 0) >>> 24;
int cardAlpha = loadedImage.getRGB(30, 50) >>> 24;
System.out.printf("Corner alpha = %d, card alpha = %d%n",
        cornerAlpha, cardAlpha);

Add this snippet after the null check in main(). The expected values are 0 for the transparent corner and 255 for the solid blue area.

Maven dependencies

AWT, Swing, and Image I/O are part of the JDK’s java.desktop module. This example needs no extra Maven dependencies. If you use a modular project, add requires java.desktop; to your module declaration.

References

Next — How do I choose an image file format in Java?