Contents

目录

@TOC

实现缩略图

在 web 开发过程中,需要对图片进行缩小,降低系统资源的压力,这样做可以提升程序的性能,和执行效率

实现方式

  • 使用 java jwt 类库
  • BufferedImage
  • ImageIO

代码

 1public class ThumbnailUtil {
 2
 3    private static final int WIDTH = 100;
 4    private static final int HEIGHT = 100;
 5
 6    /**
 7     * 等比例缩小图片
 8     *
 9     * @param file 文件
10     * @param path 输出缩略图文件路径
11     */
12    public static void thumbnail(File file, String path) {
13        if (!file.exists()) {
14            System.out.println("文件不存在");
15            return;
16        }
17        String fileName = file.getName();
18        if (path == null || path.equals("")) {
19            path = file.getParent();
20        }
21        String des = path + "/thum_" + fileName;
22        FileOutputStream os = null;
23        try {
24            os = new FileOutputStream(des);
25            BufferedImage image = ImageIO.read(file);
26            //原图宽度
27            int width = image.getWidth(null);
28            //原图高度
29            int height = image.getHeight(null);
30            int rate1 = width / WIDTH;
31            int rate2 = height / HEIGHT;
32            int rate = Math.max(rate1, rate2);
33            // 计算缩略图最终的宽度高度
34            int newWidth = width / rate;
35            int newHeight = height / rate;
36            BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
37            bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
38            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
39            ImageIO.write(bufferedImage, fileType, os);
40        } catch (IOException e) {
41            e.printStackTrace();
42        } finally {
43            if (os != null) {
44                try {
45                    os.close();
46                } catch (IOException e) {
47                    e.printStackTrace();
48                }
49            }
50        }
51    }
52}

使用

1  public static void main(String[] args) throws IOException {
2        File file = new File("E:\\images\\20.jpg");
3        thumbnail(file, null);
4    }