square thumbnails

Hi, I am trying to write a thumbnail program to create square thumbnails from an image. This would similar to thumbnails on flickr where part of the image is actually cropped out to create a square thumb. Any ideas or reference someone could point me to? Thanks!John
[287 byte] By [theboogster100a] at [2007-11-27 5:50:45]
# 1

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);

}

}

crwooda at 2007-7-12 15:38:48 > top of Java-index,Security,Cryptography...
# 2
Works great! Thanks. Related question though... I'm using this code on a remote server with no console, etc so I can't use the Graphics2D class. Any idea how to translate + scale using the methods in BufferedImage class? Thanks again.
theboogster100a at 2007-7-12 15:38:48 > top of Java-index,Security,Cryptography...