• 将图片文件转化为字节数组字符串,并对其进行Base64编码处理,以及对字节数组字符串进行Base64解码并生成图片


    实际开发中涉及图片上传并且量比较大的时候一般处理方式有三种

    1、直接保存到项目中 最老土直接方法,也是最不适用的方法,量大对后期部署很不方便

    2、直接保存到指定路径的服务器上、需要时候在获取,这种方式很方便

    3、直接保存到数据库中,需要时候解码在生成图片 下面介绍第三种方式

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

    public static String GetImageStr(File file) {
    byte[] data = null;
    // 读取图片字节数组
    try {
    InputStream in = new FileInputStream(file);
    data = new byte[in.available()];
    in.read(data);
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    // 对字节数组字符串进行Base64解码并生成图片

    public static boolean GenerateImage(String imgStr, String imgFilePath) {
    if (imgStr == null) // 图像数据为空
    return false;
    System.out.println("照片:"+imgStr);
    BASE64Decoder decoder = new BASE64Decoder();
    try {
    // Base64解码
    byte[] bytes = decoder.decodeBuffer(imgStr);
    for (int i = 0; i < bytes.length; ++i) {
    if (bytes[i] < 0) {// 调整异常数据
    bytes[i] += 256;
    }
    }
    // 生成jpeg图片
    OutputStream out = new FileOutputStream(imgFilePath);
    out.write(bytes);
    out.flush();
    out.close();
    return true;
    } catch (Exception e) {
    return false;
    }
    }

  • 相关阅读:
    多级指针类型
    核心转储(core dump)
    地址总线
    eda soa
    QT信号槽简易分析_如何查看与分析QT的源码实现
    The Meta-Object System Signals & Slots 信号槽机制
    可重入 threadsafe reentrant nonreentrant
    秘钥文件
    服务启动基本
    格言
  • 原文地址:https://www.cnblogs.com/weiyi1314/p/10413778.html
Copyright © 2020-2023  润新知