This is an open question.
Do you want to scale to fill or scale to fit the area, or doesn't the aspect ratio matter to you?
The difference between the scale for filling and scaling to match


This example will respond to frame size changes and scale the image in real time.
public class TestScaling { public static void main(String[] args) { new TestScaling(); } public TestScaling() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new ScalingPane()); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class ScalingPane extends javax.swing.JPanel { private BufferedImage image; public ScalingPane() { try { image = ImageIO.read(getClass().getResource("/AtDesk.png")); } catch (IOException ex) { ex.printStackTrace(); } setBackground(Color.red); } public double getScaleFactor(int iMasterSize, int iTargetSize) { double dScale = 1; dScale = (double) iTargetSize / (double) iMasterSize; return dScale; } public double getScaleFactorToFit(Dimension original, Dimension toFit) { double dScale = 1d; if (original != null && toFit != null) { double dScaleWidth = getScaleFactor(original.width, toFit.width); double dScaleHeight = getScaleFactor(original.height, toFit.height); dScale = Math.min(dScaleHeight, dScaleWidth); } return dScale; } public double getScaleFactorToFill(Dimension masterSize, Dimension targetSize) { double dScaleWidth = getScaleFactor(masterSize.width, targetSize.width); double dScaleHeight = getScaleFactor(masterSize.height, targetSize.height); double dScale = Math.max(dScaleHeight, dScaleWidth); return dScale; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); double scaleFactor = Math.min(1d, getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getSize()));
The best solution would be to have a background stream that can respond to component size changes and scale the original image in the background, providing low quality and quality scale.
It should also be noted that Image.getScaledInstance is neither the fastest nor the highest quality scaling algorithm. See The Perils of Image.getScaledInstance for more information.
You can also find the following interesting
Java: saving JPanel image format
Madprogrammer
source share