好得很程序员自学网

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

关于JAVA11中图片与BASE64相互转换的实现

由于jdk 1.8 之后sun.misc 包下的 BASE64Decode的依赖 被移除

我们需要在自己的项目中引入EncodeUtils 工具类 帮助我们进行转换

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class EncodeUtils {

    

     private static final String DEFAULT_URL_ENCODING = "UTF-8" ;

    

      /**

       * Base64编码.

       */

     public static String base64Encode( byte [] input) {

          return new String(Base64.encodeBase64(input));

     }

    

     /**

      * Base64解码.

      */

     public static byte [] base64Decode(String input) {

       return Base64.decodeBase64(input);

     }

}

在项目中测试

直接调用工具类中的方法即可

?

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

/***

  * <p>

  * description: base64字符串转图片

  * <p>

  * @see

  */

static void base64StringToImage(String base64String) {

     try {

         byte [] bytes1 = EncodeUtils.base64Decode(base64String);

         ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);

         BufferedImage bi1 = ImageIO.read(bais);

         File f1 = new File( "F:/wpcache/test/test.jpg" );

         ImageIO.write(bi1, "jpg" , f1);

     } catch (IOException e) {

         e.printStackTrace();

     }

}

 

/***

  * <p>

  * description:图片转base64字符串:

  * <p>

  * @see

  */

public static String getImgStr(String imgFile) {

     // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理

     InputStream in = null ;

     byte [] data = null ;

     // 读取图片字节数组

     try {

         in = new FileInputStream(imgFile);

         data = new byte [in.available()];

         in.read(data);

         in.close();

     } catch (IOException e) {

         e.printStackTrace();

     }

     return EncodeUtils.base64Encode(data);

}

在main方法中运行

?

1

2

3

4

5

public static void main(String[] args) {

     String base64Str = getImgStr( "F:/wpcache/2.jpg" );

     System.out.println(base64Str);

     base64StringToImage(base64Str);

}

运行结果

图片转BASE64 效果图

BASE64 转图片 效果图

(注:这个生成的图片路径就是自己在base64StringToImage 方法中的路径)

到此这篇关于关于JAVA11中图片与BASE64相互转换的实现的文章就介绍到这了,更多相关JAVA11图片与BASE64相互转换内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/XadminX/article/details/115858236

查看更多关于关于JAVA11中图片与BASE64相互转换的实现的详细内容...

  阅读:18次