Wednesday, May 14, 2008

Image Resizer

public static BufferedImage createResizedCopy(String imageLocation)

{

boolean preserveAlpha = true;

File originalImageFile = new File(imageLocation);

BufferedImage originalImage;

try

{

originalImage = ImageIO.read(originalImageFile);

int width;

int height;

double h = new Double(originalImage.getHeight()).doubleValue();

double w = new Double(originalImage.getWidth()).doubleValue();

double ratio = (h / w);

if (ratio > 1) // vertical (tall image)

{

height = Constants.OVERVIEW_TAB_HORIZONTAL_PHOTO_HEIGHT;

width = new Double(height / ratio).intValue();

} else

{

width = Constants.OVERVIEW_TAB_HORIZONTAL_PHOTO_WIDTH;

height = new Double(width * ratio).intValue();

}

int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

BufferedImage resizedImage = new BufferedImage(width, height, imageType);

Graphics2D g = resizedImage.createGraphics();

if (preserveAlpha)

g.setComposite(AlphaComposite.Src);

g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

g.drawImage(originalImage, 0, 0, width, height, null);

g.dispose();

return resizedImage;

} catch (IOException e)

{

System.err.println("Errors resizing the image " + imageLocation);

e.printStackTrace();

}

return null;

}