软件编程
位置:首页>> 软件编程>> java编程>> 关于JAVA11中图片与BASE64相互转换的实现

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

作者:一个不想学习的程序员  发布时间:2022-12-06 06:44:11 

标签:JAVA11,图片,BASE64,转换

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

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


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);
}
}

在项目中测试

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


/***
    * <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方法中运行


public static void main(String[] args) {
       String base64Str = getImgStr("F:/wpcache/2.jpg");
       System.out.println(base64Str);
       base64StringToImage(base64Str);
   }

运行结果

图片转BASE64 效果图

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

BASE64 转图片 效果图

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

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

来源:https://blog.csdn.net/XadminX/article/details/115858236

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com