Playframework中上传图片并按尺寸大小生成新图片
2010-10-14 09:44
447 查看
Playframework提供了一个类,Images,并且提供了一个方法,
简单看下这个方法的示例:
上传一个图片,重新生成一个120×120像素大小的图片,并存放在public/attchment/目录下。
File attachment是上传文件空间file对应的名字,和之前上传文件的一样。
/** * 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对应的名字,和之前上传文件的一样。
相关文章推荐
- 上传图片并且生成可以控制大小图片清晰度的方法
- js判断上传图片大小及尺寸
- 检验上传图片大小、尺寸、类型的两种实现方案
- ASP.NET上传图片,服务器端验证,宽度,高度,文件类型,尺寸,文件大小,图片上传,图片格式检查
- .net上传图片生成大小缩略图
- 判断上传图片的尺寸和大小demo
- C#上传图片 并按尺寸新生成一张略缩图
- 图片上传之前检查大小、尺寸、格式并预览(Validate the file size/file type/image size/ before upload)
- Asp.net获取上传图片大小的尺寸!
- js获取上传图片真实的尺寸大小和存储大小
- iTunes Connect上传APP屏幕快照图片尺寸和屏幕分辨率大小
- js获取上传图片的尺寸大小
- 前台js限制上传图片质量大小和尺寸
- js判断图片上传时的文件大小,和宽高尺寸
- php实现按指定大小等比缩放生成上传图片缩略图的方法
- php实现按指定大小等比缩放生成上传图片缩略图的方法
- 图片上传之前检查大小、尺寸、格式并预览
- 【转载】js判断上传图片大小及尺寸
- 上传图片并且生成可以控制大小图片清晰度的方法
- 关于项目中上传图片时图片尺寸和大小的判断问题