Image resizing

Hello.I am trying to draw an image to a JPanel.I whant to keep image aspect ration whenever the jpanel is resized.Can anyone help me on this isue ?Thank you
[191 byte] By [JKodera] at [2007-10-3 9:35:32]
# 1
ration=image.width/image.heightin paint component newHeight = panel.heightnew width = newHeight*ration
forumusera at 2007-7-15 4:50:58 > top of Java-index,Security,Cryptography...
# 2

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.AffineTransform;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class EasyResizing extends JPanel {

BufferedImage source, scaled;

Dimension size;

public EasyResizing(BufferedImage image) {

source = image;

scaled = image;

size = new Dimension(source.getWidth(), source.getHeight());

addComponentListener(resizer);

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,

RenderingHints.VALUE_INTERPOLATION_BICUBIC);

if(scaled == null)

createScaledImage();

g2.drawImage(scaled, 0, 0, this);

}

public Dimension getPreferredSize() {

return size;

}

private void createScaledImage() {

int w = getWidth();

int h = getHeight();

double xScale = (double)w/size.width;

double yScale = (double)h/size.height;

double scale = //Math.min(xScale, yScale); // scale to fit

Math.max(xScale, yScale);// scale to fill

// Center the scaled image.

double x = (w - scale*size.width)/2;

double y = (h - scale*size.height)/2;

AffineTransform at = AffineTransform.getTranslateInstance(x, y);

at.scale(scale, scale);

scaled = new BufferedImage(w, h, source.getType());

Graphics2D g2 = scaled.createGraphics();

// Fill background for scale to fit.

g2.setPaint(UIManager.getColor("Panel.background"));

g2.fillRect(0,0,w,h);

g2.drawRenderedImage(source, at);

g2.dispose();

}

public static void main(String[] args) throws IOException {

BufferedImage image = ImageIO.read(new File("images/owls.jpg"));

EasyResizing test = new EasyResizing(image);

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(test);

f.pack();

f.setLocation(200,200);

f.setVisible(true);

}

private ComponentListener resizer = new ComponentAdapter() {

public void componentResized(ComponentEvent e) {

scaled = null;

repaint();

}

};

}

crwooda at 2007-7-15 4:50:58 > top of Java-index,Security,Cryptography...