import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
public class Resizing {
private JPanel getContent(BufferedImage image) {
JLabel left = getLabel(100, 75, image);
JLabel right = getLabel(90, 160, image);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
panel.add(left, gbc);
panel.add(right, gbc);
return panel;
}
private JLabel getLabel(int w, int h, BufferedImage image) {
BufferedImage scaled = scale(image, w, h);
JLabel label = new JLabel(new ImageIcon(scaled));
label.setPreferredSize(new Dimension(w, h));
label.setBorder(BorderFactory.createEtchedBorder());
return label;
}
private BufferedImage scale(BufferedImage src, int w, int h) {
int type = BufferedImage.TYPE_INT_RGB;
BufferedImage dst = new BufferedImage(w, h, type);
Graphics2D g2 = dst.createGraphics();
// Fill background for scale to fit.
g2.setBackground(UIManager.getColor("Panel.background"));
g2.clearRect(0,0,w,h);
double xScale = (double)w/src.getWidth();
double yScale = (double)h/src.getHeight();
// Scaling options:
// Scale to fit - image just fits in label.
double scale = Math.min(xScale, yScale);
// Scale to fill - image just fills label.
//double scale = Math.max(xScale, yScale);
int width = (int)(scale*src.getWidth());
int height = (int)(scale*src.getHeight());
int x = (w - width)/2;
int y = (h - height)/2;
g2.drawImage(src, x, y, width, height, null);
g2.dispose();
return dst;
}
public static void main(String[] args) throws IOException {
File file = new File("images/bison.jpg");
BufferedImage image = javax.imageio.ImageIO.read(file);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Resizing().getContent(image));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
by. Craig Wood
Ranch Hand
posted Sunday, July 06, 2008 05:21pm