zoukankan      html  css  js  c++  java
  • 将图片文件转化为字节数组字符串,并对其进行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;
    }
    }

  • 相关阅读:
    noip2017逛公园
    [noip模拟赛]小U的女装
    AT2364 Colorful Balls
    关于bitset
    [ZJOI2010]排列计数
    [noip模拟赛]午餐
    [noip2017]列队
    [学习笔记]dsu on a tree(如何远离线段树合并)
    luogu4917天守阁的地板
    线性求素数+莫比乌斯函数+欧拉函数模板
  • 原文地址:https://www.cnblogs.com/weiyi1314/p/10413778.html
Copyright © 2011-2022 走看看