好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现压缩图片大小

本文实例为大家分享了Java实现压缩图片大小的具体代码,供大家参考,具体内容如下

使用场景:

1.当使用图片上传功能时,上传图片太大,造成对服务器资源过多的占用
2.客户端上传图片尺寸大小不一,前端需要展示给用户固定尺寸时,可通过java进行对上传图片统一进行处理

功能预览

1.压缩前

2.压缩后

代码实现:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

package com.linghu.test;

 

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

 

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

 

/*

  * @author 在下令狐

  * @describe  压缩图片大小

  * @date 2020/6/12

  */

public class TestCompressImage {

    public static void main(String[] args) {

        try {

            //图片所在路径

            BufferedImage templateImage = ImageIO.read( new File( "f:/temp/linghu.jpg" ));

 

 

            //原始图片的长度和宽度

            int height = templateImage.getHeight();

            int width = templateImage.getWidth();

 

            //通过比例压缩

            float scale = 0 .5f;

 

            //通过固定长度压缩

            /*int doWithHeight = 100;

            int dowithWidth = 300;*/

 

            //压缩之后的长度和宽度

            int doWithHeight = ( int ) (scale * height);

            int dowithWidth = ( int ) (scale * width);

 

            BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);

 

            finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0 , 0 , null );

 

 

            //图片输出路径,以及图片名

            FileOutputStream  fileOutputStream = new FileOutputStream( "f:/temp/linghuAfterDoWith.jpg" );

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);

            encoder.encode(finalImage);

            fileOutputStream.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/yang353933546/article/details/106722543

查看更多关于Java实现压缩图片大小的详细内容...

  阅读:13次