import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SquareThumb {
private JPanel getContent(BufferedImage image) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
gbc.weightx = 1.0;
panel.add(new JLabel(new ImageIcon(image)), gbc);
panel.add(new JLabel(new ImageIcon(getFillThumb(image))), gbc);
panel.add(new JLabel(new ImageIcon(getCropThumb(image))), gbc);
return panel;
}
private BufferedImage getFillThumb(BufferedImage src) {
int w = 100;
int h = 100;
int type = BufferedImage.TYPE_INT_RGB;
// src.getType();
BufferedImage dest = new BufferedImage(w, h, type);
Graphics2D g2 = dest.createGraphics();
int iw = src.getWidth();
int ih = src.getHeight();
double xScale = (double)w/iw;
double yScale = (double)h/ih;
double scale = Math.max(xScale, yScale);
double x = (w - scale*iw)/2;
double y = (h - scale*ih)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.scale(scale, scale);
g2.drawRenderedImage(src, at);
g2.dispose();
return dest;
}
private BufferedImage getCropThumb(BufferedImage src) {
int w = 100;
int h = 100;
int type = BufferedImage.TYPE_INT_RGB;
// src.getType();
BufferedImage dest = new BufferedImage(w, h, type);
Graphics2D g2 = dest.createGraphics();
int iw = src.getWidth();
int ih = src.getHeight();
double x = (iw - w)/2.0;
double y = (ih - h)/2.0;
AffineTransform at = AffineTransform.getTranslateInstance(-x, -y);
g2.drawRenderedImage(src, at);
g2.dispose();
return dest;
}
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("images/cougar.jpg"));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new SquareThumb().getContent(image));
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}