您的位置:首页 > 其它

Playframework中上传图片并按尺寸大小生成新图片

2010-10-14 09:44 447 查看
Playframework提供了一个类,Images,并且提供了一个方法,

/**
* Resize an image
* @param originalImage The image file
* @param to The destination file
* @param w The new width (or -1 to proportionally resize)
* @param h The new height (or -1 to proportionally resize)
*/
public static void resize(File originalImage, File to, Integer w, Integer h) {
try {
BufferedImage source = ImageIO.read(originalImage);
int owidth = source.getWidth();
int oheight = source.getHeight();
double ratio = (double) owidth / oheight;
if (w < 0 && h < 0) {
w = owidth;
h = oheight;
}
if (w < 0 && h > 0) {
w = (int) (h * ratio);
}
if (w > 0 && h < 0) {
h = (int) (w / ratio);
}
String mimeType = "image/jpeg";
if (to.getName().endsWith(".png")) {
mimeType = "image/png";
}
if (to.getName().endsWith(".gif")) {
mimeType = "image/gif";
}
// out
BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Image srcSized = source.getScaledInstance(w, h, Image.SCALE_SMOOTH);
Graphics graphics = dest.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, w, h);
graphics.drawImage(srcSized, 0, 0, null);
ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
ImageWriteParam params = writer.getDefaultWriteParam();
FileImageOutputStream toFs = new FileImageOutputStream(to);
writer.setOutput(toFs);
IIOImage image = new IIOImage(dest, null, null);
writer.write(null, image, params);
toFs.flush();
toFs.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}


简单看下这个方法的示例:

public static void imageresize(File attachment){
if(request.method.equalsIgnoreCase("POST")){
Images.resize(attachment, Play.getFile("public/attachment/" + attachment.getName()), 120, 120);
render();
}else{
render();
}
}


上传一个图片,重新生成一个120×120像素大小的图片,并存放在public/attchment/目录下。

File attachment是上传文件空间file对应的名字,和之前上传文件的一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: