栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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;
 

public class ImageUtils {
  
  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编码过的字节数组字符串
  }
 
  
  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编码过的字节数组字符串
  }
 
  
  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编码的图片

 
 
  
 
 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134681.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号