好得很程序员自学网

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

Java修改图片大小尺寸的简单实现

方式一:使用Image.getScaledInstance

使用jdk的awt包下的Image.getScaledInstance实现 图片 的缩放。好处是无需引入第三方jar,缺点是会稍微有点模糊。

工具类ImageUtils:

?

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

package utils;

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

public class ImageUtils {

     /**

      * 通过BufferedImage图片流调整图片 大小

      */

     public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {

         Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);

         BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);

         outputImage.getGraphics().drawImage(resultingImage, 0 , 0 , null );

         return outputImage;

     }

     /**

      * BufferedImage图片流转byte[]数组

      */

     public static byte [] imageToBytes(BufferedImage bImage) {

         ByteArrayOutputStream out = new ByteArrayOutputStream();

         try {

             ImageIO.write(bImage, "jpg" , out);

         } catch (IOException e) {

             e.printStackTrace();

         }

         return out.toByteArray();

     }

     /**

      * byte[]数组转BufferedImage图片流

      */

     private static BufferedImage bytesToBufferedImage( byte [] ImageByte) {

         ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);

         BufferedImage image = null ;

         try {

             image = ImageIO.read(in);

         } catch (IOException e) {

             e.printStackTrace();

         }

         return image;

     }

}

测试

1.通过 url 获取图片并调整大小后保存:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import utils.ImageUtils;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.net.URL;

public class Test {

     public static void main(String[] args) {

         try {

             //通过url获取BufferedImage图像缓冲区

             URL img = new URL( "https://img1.360buyimg测试数据/image/jfs/t1/38591/20/3737/314695/5cc69c01E1838df09/dd6dce681bd23031.jpg" );

             BufferedImage image = ImageIO.read(img);

             //获取图片的宽、高

             System.out.println( "Width: " + image.getWidth());

             System.out.println( "Height: " + image.getHeight());

             //调整图片大小为 400X400 尺寸

             BufferedImage newImage = ImageUtils.resizeImage(image, 400 , 400 );

             //将缓冲区图片保存到 F:/test/pic1.jpg (文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)

             ImageIO.write(newImage, "jpg" , new File( "F:/test/pic1.jpg" ));

         } catch (IOException e) {

             e.printStackTrace();

         }

     }

}

2.通过读取图片文件调整大小再保存:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import utils.ImageUtils;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class Test {

     public static void main(String[] args) {

         try {

             //读取原始图片

             BufferedImage image = ImageIO.read( new FileInputStream( "F:/test/pic1.jpg" ));

             System.out.println( "Width: " + image.getWidth());

             System.out.println( "Height: " + image.getHeight());

             //调整图片大小

             BufferedImage newImage = ImageUtils.resizeImage(image, 200 , 200 );

             //图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)

             ImageIO.write(newImage, "jpg" , new File( "F:/test/pic2.jpg" ));

         } catch (IOException e) {

             e.printStackTrace();

         }

     }

}

3.MultipartFile类型的图片文件调整大小再保存:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public JSONObject imageSizeAdjustment(MultipartFile file) {

        JSONObject result = new JSONObject();

        try {

            //从MultipartFile 中获取 byte[]

            byte [] bytes = file.getBytes();

            //byte[]转 InputStream

            InputStream in = new ByteArrayInputStream(bytes);

            //读取图片输入流为 BufferedImage

            BufferedImage image = ImageIO.read(in);

            System.out.println( "Width: " + image.getWidth());

            System.out.println( "Height: " + image.getHeight());

            //调整图片大小

            BufferedImage newImage = ImageUtils.resizeImage(image, 200 , 200 );

            //图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)

            ImageIO.write(newImage, "jpg" , new File( "F:/test/pic2.jpg" ));

        } catch (IOException e) {

            e.printStackTrace();

        }

        result.put( "code" , 1 );

        result.put( "note" , "成功" );

        return result;

    }

方式二:使用Thumbnailator

Thumbnailator是 Java 的开源图像大小调整库,它使用渐进式双线性缩放。它支持JPG,BMP,JPEG,WBMP,PNG和GIF。

通过将以下Maven依赖项添加到我们的pom.xml中,将其包括在我们的项目中:

?

1

2

3

4

5

< dependency >

     < groupId >net.coobird</ groupId >

     < artifactId >thumbnailator</ artifactId >

     < version >0.4.11</ version >

</ dependency >

工具类ThumbnailsUtils:

?

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

import net.coobird.thumbnailator.Thumbnails;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

public class ThumbnailsUtils{

     private static final Logger logger = LoggerFactory.getLogger(ThumbnailsUtils. class );

     /**

      * 通过BufferedImage图片流调整图片大小

      */

     public static BufferedImage resizeImageOne(BufferedImage originalImage, int targetWidth, int targetHeight) throws Exception {

         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

         Thumbnails.of(originalImage)

                 .size(targetWidth, targetHeight)

                 .outputFormat( "JPEG" )

                 .outputQuality( 1 )

                 .toOutputStream(outputStream);

         byte [] data = outputStream.toByteArray();

         ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

         return ImageIO.read(inputStream);

     }

   

     /**

      * BufferedImage图片流转byte[]数组

      */

     public static byte [] imageToBytes(BufferedImage bImage) {

         ByteArrayOutputStream out = new ByteArrayOutputStream();

         try {

             ImageIO.write(bImage, "jpg" , out);

         } catch (IOException e) {

             logger.error( "错误信息: " , e);

         }

         return out.toByteArray();

     }

     /**

      * byte[]数组转BufferedImage图片流

      */

     private static BufferedImage bytesToBufferedImage( byte [] ImageByte) {

         ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);

         BufferedImage image = null ;

         try {

             image = ImageIO.read(in);

         } catch (IOException e) {

             logger.error( "错误信息: " , e);

         }

         return image;

     }

}

测试

和上面测试基本一样只不过 ImageUtils.resizeImage换成 ThumbnailsUtils.resizeImageOne即可。

最终效果:

原图:

长宽缩为原来的三分之一后的图:

如果需要将 BufferedImage 转换为 MultipartFile,请参考我另一篇文章:

BufferedImage转换为MultipartFile

其他图片大小调整方法请参考:

How Can I Resize an Image Using Java

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_33697094/article/details/114327979

查看更多关于Java修改图片大小尺寸的简单实现的详细内容...

  阅读:25次