java图像处理工具----thumbnailator-0.4.8.jar

很久没更新了,今天我在做缩略图时发现有很多图片在剪切压缩后失真了,变的模糊了,在找了好久也对比了好几种方法后才确定下来了这个工具:thumbnailator-0.4.8.jar,想要安装包以及其他问题的联系本人qq:1814148326

不说废话了直接上代码:

public class Test {

    public static void main(String[] args) {

        String url = "D:\\图片\\1617893086925.png";

        cutDownSize(url, "D:\\a.png", 224, 126);

        cutDownScale(url, "D:\\b.png",0.57);

    }

    /**

    * 指定大小进行缩放

    * @param sourceFile 需要压缩的图片地址

    * @param targetFile 压缩完成的图片地址

    * @param width 压缩宽度

    * @param height 压缩高度

    */

    public static void cutDownSize(String sourceFile, String targetFile, Integer width, Integer height) {

        try {

            Thumbnails.of(sourceFile).size(width, height).keepAspectRatio(false).toFile(targetFile);

        } catch (IOException e) {

        System.out.println("图片处理异常");

        }

    }

    //

    /**

    * 指定比例进行缩放

    * @param sourceFile 需要压缩的图片地址

    * @param targetFile 压缩完成的图片地址

    * @param scale 压缩比例

    */

    public static void cutDownScale(String sourceFile, String targetFile, Double scale) {

        try {

            Thumbnails.of(sourceFile).scale(scale).toFile(targetFile);

        } catch (IOException e) {

        System.out.println("图片处理异常");

        }

    }

    /**

    * 按照大小中心裁剪

    * @param sourceFile

    * @param targetFile

    * @param x

    * @param y

    */

    public static void cut(String sourceFile, String targetFile, Integer x, Integer y) {

        try {

            Thumbnails.of(sourceFile).sourceRegion(Positions.CENTER,x,y).size(500,500).outputFormat("JPEG").toFile(targetFile);

        } catch (IOException e) {

        System.out.println("图片处理异常");

        }

    }

    /**

    * 根据传入的参数进行裁剪+压缩

    * @param sourceFile 需要压缩的图片地址

    * @param targetFile 压缩完成的图片地址

    * @param x 图片中心切割比例

    * @param y 图片中心切割比例

    * @param width 压缩的宽度

    * @param height 压缩的高度

    */

    public static void cutDownOut(String sourceFile, String targetFile, Integer x, Integer y,

                              Integer width, Integer height) {

        try {

            Thumbnails.of(sourceFile).sourceRegion(Positions.CENTER,x,y).size(width, height).keepAspectRatio(false)

                    .toFile(targetFile);

        } catch (IOException e) {

            System.out.println("图片处理异常");

        }

    }

}

我只测试了第一个和第二个,给大家看看效果图:

原图681 KB


截取压缩后224*126(57.3kb)


等比例缩放0.57后346kb

直接看效果最明显;在我们开发网站的时候加载图片的速度很重要,这让我们更快的去渲染;

欢迎大家前来咨询。

qq群:311602501

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容