Java处理图片实现base64编码转换

2020-09-23 0 949

前言

环境:使用这个代码前:请确保你的JDk是JAVA8及其以上

开发测试地址:http://imgbase64.duoshitong.com/ 可以查看是否执行成功

Java处理图片实现base64编码转换

注意事项

一般插件返回的base64编码的字符串都是有一个前缀的。\”data:image/jpeg;base64,\” 解码之前这个得去掉。

Code

MainTest

/**
   * 示例
   * @throws UnsupportedEncodingException 
   * @throws FileNotFoundException 
   */
  @SuppressWarnings(\"resource\")
  public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
    String strImg = getImageStr(\"Z:\\\\水印\\\\2.bmp\");
    System.out.println(strImg);
    File file = new File(\"z://1.txt\");
    FileOutputStream fos = new FileOutputStream(file);
    OutputStreamWriter osw = new OutputStreamWriter(fos, \"UTF-8\");
    try {
      osw.write(strImg);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //generateImage(strImg, \"Z:\\\\水印\\\\444.bmp\");
    
  }

加密:

**
   * @Description: 根据图片地址转换为base64编码字符串
   * @Author:
   * @CreateTime:
   * @return
   */
  public static String getImageStr(String imgFile) {
    InputStream inputStream = null;
    byte[] data = null;
    try {
      inputStream = new FileInputStream(imgFile);
      data = new byte[inputStream.available()];
      inputStream.read(data);
      inputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 加密
    Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(data);
  }

解密:

/**
   * @Description: 将base64编码字符串转换为图片
   * @Author: 
   * @CreateTime: 
   * @param imgStr base64编码字符串
   * @param path 图片路径-具体到文件
   * @return
  */
  public static boolean generateImage(String imgStr, String path) {
      if (imgStr == null)
        return false;
      // 解密
      try {
        Decoder decoder = Base64.getDecoder();
        byte[] b = decoder.decode(imgStr);
        // 处理数据
        for (int i = 0; i < b.length; ++i) {
          if (b[i] < 0) {
          b[i] += 256;
          }
        }
        OutputStream out = new FileOutputStream(path);
        out.write(b);
        out.flush();
        out.close();
        return true;
      } catch (IOException e) {
        return false;
      }
  }

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

遇见资源网 JAVA Java处理图片实现base64编码转换 http://www.ox520.com/18532.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务