Java 缩略图

产品提出一个新需求,上传文件的时候需要根据原图生成缩略图一并返回前端

对比下Java原生类和Thumbnails创建缩略图做个对比,发现Thumbnails真香···

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;


/**
 * 使用JDK原生态类生成图片缩略图和裁剪图片
 */
public class ImageUtil1 {

    /**
     * 生成缩略图的前缀
     */
    private static String DEFAULT_PREFIX = "thumb_";

    /**
     * 是否需要生成最适合比例
     */
    private static Boolean DEFAULT_FORCE = true;

    /**
     * 根据图片路径生成缩略图
     * @param imgFile 原图片路径
     * @param w 缩略图宽
     * @param h 缩略图高
     */
    public static void thumbnailImage(File imgFile, int w, int h) {
        if(imgFile.exists()){
            try {
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames());
                String suffix = null;
                // 获取图片后缀
                if(imgFile.getName().contains(".")) {
                    suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
                }
                // 类型和图片后缀全部小写,然后判断后缀是否合法
                if(suffix == null || !types.toLowerCase().contains(suffix.toLowerCase())){
                    System.out.println("Sorry, the image suffix is illegal");
                    return;
                }
                Image img = ImageIO.read(imgFile);
                if(DEFAULT_FORCE) {
                    // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
                    int width = img.getWidth(null);
                    int height = img.getHeight(null);
                    if((width * 1.0) / w < (height * 1.0) / h) {
                        if(width > w) {
                            h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
                        }
                    } else {
                        if(height > h) {
                            w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0)));
                        }
                    }
                }
                BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
                g.dispose();
                String p = imgFile.getPath();
                // 将图片保存在原目录并加上前缀
                ImageIO.write(bi, suffix, new File(p.substring(0, p.lastIndexOf(File.separator)) + File.separator + DEFAULT_PREFIX + imgFile.getName()));
            } catch (IOException e) {
                System.out.println("generate thumbnail image failed");
            }
        }
    }


    public static void main(String[] args) {
        File file = new File("D:\test\test.jpg");
        thumbnailImage(file, 150, 150);
    }

}
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImageUtil2 {

    /**
     * 取得图片对象
     * 要转化的图像的文件夹,就是存放图像的文件夹路径
     */
    private BufferedImage zoomImage(BufferedImage im, int toWidth, int toHeight) {
        BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
        result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return result;
    }


    /**
     * 取得图片对象
     * 要转化的图像的文件夹,就是存放图像的文件夹路径
     */
    private BufferedImage getImageList(String ImgList, String[] type) {
        Map<String, Boolean> map = new HashMap<>();
        for (String s : type) {
            map.put(s, true);
        }
        BufferedImage imageList = null;
        File file = new File(ImgList);
        try {
            if (file.length() != 0 && map.get(getExtension(file.getName())) != null) {
                imageList = javax.imageio.ImageIO.read(file);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return imageList;
    }

    /**
     * 把图片写到磁盘上
     * @param path 图片写入的文件夹地址
     * @param fileName 写入图片的名字
     */
    public boolean writeToDisk(BufferedImage im, String path, String fileName) throws IOException {
        File f = new File(path + fileName);
        String fileType = getExtension(fileName);

        if (StringUtils.isNotEmpty(fileType)) {
            ImageIO.write(im, fileType, f);
            im.flush();
            return true;
        }
        return false;
    }

    /**
     * 生成图片
     */
    private boolean writeHighQuality(String path, BufferedImage im, String fileFullPath) {
        FileOutputStream newImageStream;
        try {
            // 输出到文件流
            newImageStream = new FileOutputStream(fileFullPath + path);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImageStream);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
            // 压缩质量
            jep.setQuality(1f, true);
            encoder.encode(im, jep);
            // 近JPEG编码
            newImageStream.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 取文件名的后缀
     * @param fileName 格式如:cn1100000213EA_1_xnl.jpg
     * @date 2020-08-13
     */
    private String getExtension(String fileName) {
        try {
            return fileName.split("\.")[fileName.split("\.").length - 1];
        } catch (Exception e) {
            return null;
        }
    }


    public static void main(String[] args) {
        // windows路径,linux环境下相应修改
        String outputFolder = "D:\test\";
        String fileName = "D:\test\test.jpg";
        ImageUtil2 r = new ImageUtil2();
        int toWidth = 220, toHeight = 220;

        BufferedImage imageList = r.getImageList(fileName, new String[]{"jpg", "png", "gif"});
        r.writeHighQuality("newFile.jpg", r.zoomImage(imageList, toWidth, toHeight), outputFolder);
    }
}
import net.coobird.thumbnailator.Thumbnails;

import java.io.IOException;

public class ThumbnailsUtil {

    public static void main(String[] args) throws IOException {
        /*
         * 指定大小进行缩放
         * 若图片横比200小,高比300小,不变
         * 若图片横比200小,高比300大,高缩小到300,图片比例不变
         * 若图片横比200大,高比300小,横缩小到200,图片比例不变
         * 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300
         */
        Thumbnails.of("D:\test\test.jpg")
                .size(200, 300)
                .toFile("D:\test\test123.jpg");


        /*
         * 按照比例进行缩放
         * scale(比例)
         * 如果scale设为1.0,则图片长宽不变
         */
        Thumbnails.of("D:\test\test.jpg")
                .scale(0.25f)
                .toFile("D:\test\test123.jpg");
        Thumbnails.of("D:\test\test.jpg")
                .scale(1.0f)
                .toFile("D:\test\test123.jpg");


        /*
         * 不按照比例,指定大小进行缩放
         * keepAspectRatio(false) 默认是按照比例缩放的
         */
        Thumbnails.of("D:\test\test.jpg")
                .size(200, 200)
                .keepAspectRatio(false)
                .toFile("D:\test\test123.jpg");

        /*
         * 还有旋转、水印、裁剪等等功能
         */
    }

    
}

JAVA生成略缩图:
https://blog.csdn.net/leo187/article/details/79197952
https://www.cnblogs.com/icerainsoft/p/4056393.html
https://www.imooc.com/article/details/id/21790
Thumbnailator的简介和使用范例:
https://www.xuebuyuan.com/3229489.html
https://www.jianshu.com/p/ad8af8214e60
ImageIo类常用方法以及图片操作:
https://blog.csdn.net/baidu_28665563/article/details/82887485

原文地址:https://www.cnblogs.com/hzzjj/p/13497387.html