最近负责组内的图片上传相关的业务,有了一个新的需求,大概要做的功能是要实现gif图片有裁剪的功能,一想到咋自个对图片这种数据结构不是很熟,所以找开源项目吧。终于找到了gif4j这样一个项目。于是乎作者立马将它fock了一下,然后改造成了自己的项目。最后的裁剪效果如下,基本达到了要求了。
原图
裁剪
压缩
新增的maven依赖:
<dependency> <groupId>javax.media</groupId> <artifactId>jai-core</artifactId> <version>1.1.3</version> </dependency>
<dependency> <groupId>com.sun.media</groupId> <artifactId>jai-codec</artifactId> <version>1.1.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.10.0</version> </dependency>
在功能实现之后,作者将自己的修改新建了一个包。如图:
测试代码如下:
/** * @param args * @throws Exception */public static void main(String[] args) throws Exception { try { // 起始坐标,剪切大小 int x = 0; int y = 0; int width = 100; int height = 100; // 参考图像大小 int clientWidth = 300; int clientHeight = 250;
File file = new File("C:\\Users\\tianjingle\\Desktop\\0.gif"); BufferedImage image = ImageIO.read(file); double destWidth = image.getWidth(); double destHeight = image.getHeight();
if(destWidth < width || destHeight < height) { throw new Exception("源图大小小于截取图片大小!"); }
double widthRatio = destWidth / clientWidth; double heightRatio = destHeight / clientHeight;
x = Double.valueOf(x * widthRatio).intValue(); y = Double.valueOf(y * heightRatio).intValue(); width = Double.valueOf(width * widthRatio).intValue(); height = Double.valueOf(height * heightRatio).intValue();
System.out.println("裁剪大小 x:" + x + ",y:" + y + ",width:" + width + ",height:" + height); float ratio = ((float) image.getWidth()) / image.getWidth(); String formatName = "gif"; String pathSuffix = "." + formatName; String pathPrefix = "C:\\Users\\tianjingle\\Desktop\\"; String targetPath = pathPrefix + System.currentTimeMillis() + pathSuffix; byte[] target = ImageUtils.cutImage(new FileInputStream(file.getPath()), "gif", x , y , width, height,ratio); FileUtils.writeByteArrayToFile(new File(targetPath),target); } catch (IOException e) { e.printStackTrace(); }}
详细情况见代码:https://github.com/tianjingle/gif4j
早~