zoukankan      html  css  js  c++  java
  • base64字符串转化成图片

    package com.dhht.wechat.util;

    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;

    import java.io.*;

    /**
    * @Author: sh
    * @Description: ImgUtil
    * @Date: 9:14 2019/7/1
    */
    public class ImgUtil {


    /**
    * 图片转化成base64字符串
    *
    * @param imgPath
    * @return
    */
    public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    String imgFile = imgPath;// 待处理的图片
    InputStream in = null;
    byte[] data = null;
    String encode = null; // 返回Base64编码过的字节数组字符串
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    try {
    // 读取图片字节数组
    in = new FileInputStream(imgFile);
    data = new byte[in.available()];
    in.read(data);
    encode = encoder.encode(data);
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    in.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return encode;
    }

    /**
    * base64字符串转化成图片
    *
    * @param imgData 图片编码
    * @param imgFilePath 存放到本地路径
    * @return
    * @throws IOException
    */
    @SuppressWarnings("finally")
    public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
    if (imgData == null) // 图像数据为空
    return false;
    BASE64Decoder decoder = new BASE64Decoder();
    OutputStream out = null;
    try {
    out = new FileOutputStream(imgFilePath);
    // Base64解码
    byte[] b = decoder.decodeBuffer(imgData);
    for (int i = 0; i < b.length; ++i) {
    if (b[i] < 0) {// 调整异常数据
    b[i] += 256;
    }
    }
    out.write(b);
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {
    out.flush();
    out.close();
    return true;
    }
    }
    }
  • 相关阅读:
    PreparedStatement/Statement处理insert update等操作时乱码,以及URL
    MySQL unique 注意
    web乱码解决了
    实用工具及Chrome插件及实用网站(持续更新中...)
    前端常用算法集合,持续更新...
    各种问题汇总解决方法,持续更新中...
    node实现自动化图片切割压缩, 部署页面
    移动端图片缩放插件Pinchzoom.js
    提示框简单封装
    模拟滚动条
  • 原文地址:https://www.cnblogs.com/sung1024/p/11391965.html
Copyright © 2011-2022 走看看