前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java实现gif图片剪裁

java实现gif图片剪裁

作者头像
写一点笔记
发布2022-08-11 16:52:41
1.1K0
发布2022-08-11 16:52:41
举报
文章被收录于专栏:程序员备忘录程序员备忘录

最近负责组内的图片上传相关的业务,有了一个新的需求,大概要做的功能是要实现gif图片有裁剪的功能,一想到咋自个对图片这种数据结构不是很熟,所以找开源项目吧。终于找到了gif4j这样一个项目。于是乎作者立马将它fock了一下,然后改造成了自己的项目。最后的裁剪效果如下,基本达到了要求了。

原图

裁剪

压缩

新增的maven依赖:

代码语言:javascript
复制

        <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>
在功能实现之后,作者将自己的修改新建了一个包。如图:

测试代码如下:

代码语言:javascript
复制
/**
 * @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

早~

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-06-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 写点笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档