четверг, 20 марта 2008 г.

Правильное изменение размера картинки с использованием JAVA

Сегодня на работе была поставлена такая задача. При загрузке фотографии на сайт, должен производиться ресайз до определенного размера, причем пропорционально. Лишние края должны обрезаться. Ниже привожу как это реализовано. Коротко опишу как рабоатет метод.

1. Передается путь к файлу изображения на сервере.
2. С использованием setSize картинка приводится к нужному размеру.
3. Строка resImage.getGraphics().drawImage(outputImage,0,0,dowidth,doheight,sx1,sy1,sx1+dowidth,sy1+doheight,null); используется для обрезания краев фотографии.

public static void do_small_corp(String filePath, int dowidth, int doheight)
throws java.io.IOException {
Image inputImage = Toolkit.getDefaultToolkit().getImage(filePath);
ImageSizer.checkImage( inputImage );
int im_width = inputImage.getWidth(null);
int im_height = inputImage.getHeight(null);

Image outputImage = null;

if ((im_width>dowidth) (im_height>doheight))
{
if (im_width<im_height)
{
outputImage = ImageSizer.setSize(inputImage, dowidth, -1);
}
else {
outputImage = ImageSizer.setSize(inputImage, -1, doheight);
}
} else {
outputImage = ImageSizer.setSize(inputImage, im_width, im_height);
}
ImageSizer.checkImage( outputImage );
int new_width = outputImage.getWidth(null);
int new_height = outputImage.getHeight(null);
System.err.println("Image size do: "+dowidth+" x "+doheight);
System.err.println("Image siz new: "+new_width+" x "+new_height);
int sx1=0;
int sy1=0;
if (new_width>dowidth) sx1=new_width/2-dowidth/2;
if (new_height>doheight) sy1=new_height/2-doheight/2;
System.err.println("SX SY: "+sx1+" x "+sy1);
Image resImage = null;
Frame f = new Frame();
f.setVisible(true);
resImage = f.createImage(dowidth, doheight);
resImage.getGraphics().drawImage(outputImage,
0,0,dowidth,doheight,sx1,sy1,sx1+dowidth,sy1+doheight,null);
f.setVisible(false);
// Encode JPEG file.
FileOutputStream fos = new FileOutputStream(
filePath.substring(0,filePath.lastIndexOf("."))+
""+filePath.substring(filePath.lastIndexOf(".")));
ImageSizer.encodeJPEG( fos, resImage, 1);
fos.close();
} // do_small
public static Image setSize( Image image, int width, int height ) {
return setSize( image, width, height, 2);
} // setSize
/** Adjusts the size of the image to the given coordinates.
* If width or height is -1, the image aspect ration is maintained.
* <p>
* Hints are one of SCALE_DEFAULT, SCALE_FAST, SCALE_SMOOTH,
* SCALE_REPLICATE, SCALE_AREA_AVERAGING as defined in java.awt.Image.
*/
public static Image setSize( Image image, int width, int height, int hints ) {
return image.getScaledInstance( width, height, Image.SCALE_SMOOTH );
} // setSize

Сразу скажу, что задача не стояла сделать ресайз (resize+corp) самым оптимальным способом, поэтому извиняйте.