java实现gif图片剪裁

最近负责组内的图片上传相关的业务,有了一个新的需求,大概要做的功能是要实现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

早~

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值