Java Base64编码解码 Java基于Base64实现编码解码图片文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java Base64编码解码 Java基于Base64实现编码解码图片文件

NemoWang   2021-04-21 我要评论

BASE64 编码是一种常用的字符编码,在很多地方都会用到。但base64不是安全领域下的加密解密算法。能起到安全作用的效果很差,而且很容易破解,他核心作用应该是传输数据的正确性,有些网关或系统只能使用ASCII字符。Base64就是用来将非ASCII字符的数据转换成ASCII字符的一种方法,而且base64特别适合在http,mime协议下快速传输数据。

1、编码与解码代码如下所示:

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
 
import javax.imageio.ImageIO;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
/**
 * @author zxn
 * @version 创建时间:2014-7-2 上午11:40:40
 * 
 */
public class ImageUtils {
  /**
   * 将网络图片进行Base64位编码
   * 
   * @param imgUrl
   *      图片的url路径,如http://.....xx.jpg
   * @return
   */
  public static String encodeImgageToBase64(URL imageUrl) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    ByteArrayOutputStream outputStream = null;
    try {
      BufferedImage bufferedImage = ImageIO.read(imageUrl);
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage, "jpg", outputStream);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
  }
 
  /**
   * 将本地图片进行Base64位编码
   * 
   * @param imgUrl
   *      图片的url路径,如http://.....xx.jpg
   * @return
   */
  public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    ByteArrayOutputStream outputStream = null;
    try {
      BufferedImage bufferedImage = ImageIO.read(imageFile);
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage, "jpg", outputStream);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
  }
 
  /**
   * 将Base64位编码的图片进行解码,并保存到指定目录
   * 
   * @param base64
   *      base64编码的图片信息
   * @return
   */
  public static void decodeBase64ToImage(String base64, String path,
      String imgName) {
    BASE64Decoder decoder = new BASE64Decoder();
    try {
      FileOutputStream write = new FileOutputStream(new File(path
          + imgName));
      byte[] decoderBytes = decoder.decodeBuffer(base64);
      write.write(decoderBytes);
      write.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

2、直接在页面上显示base64编码的图片

 <html>
 <body>
 <img src='data:image/jpg;base64,base64码'/> 
 </body>
 </html>

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们