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

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.

