WEB实战:头像裁剪
?
参考http://deepliquid.com/projects/Jcrop/demos.php?demo=handler,代码如下:
var showCoords = function(c){ $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); } $('#jcrop_target').Jcrop({ onChange:showCoords, onSelect:showCoords });
获取截图区域的坐标信息,这里需要考虑图片长宽的缩放比例,计算好准确的数值(x、y、w、h)传给服务器,由java类在原图的基础上进行裁剪。
1.根据图片File对象或者流,转换成BufferedImage对象
BufferedImage bi = ImageIO.read(file);或者ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());BufferedImage bi = ImageIO.read(bis);
ImageIO还支持其它参数如下:
?
2.获取ImageWriter
private static ImageWriter getImageWriter(BufferedImage bi) { ImageWriter writer = null; ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(bi); Iterator iter = ImageIO.getImageWriters(type, "jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } return writer;}
?
3.设置Writer参数
ImageWriteParam param = writer.getDefaultWriteParam();param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);param.setCompressionQuality((float) 1.0);param.setSourceRegion(new Rectangle(x, y, width, height));
?
4.输出Image文件或者流
IIOImage iioImage = new IIOImage(bi, null, null);ByteArrayOutputStream bos2 = new ByteArrayOutputStream();ImageOutputStream outputStream = ImageIO.createImageOutputStream(bos2);writer.setOutput(outputStream);writer.write(null, iioImage, param);
?
5.将流对象保存到文件系统
?