当前位置: 移动技术网 > IT编程>开发语言>Java > 图片与Base64的转换

图片与Base64的转换

2019年02月17日  | 移动技术网IT编程  | 我要评论
图片转为Base64 Base64转为图片 这里在转码时,使用正则表达式自动甄别图片是什么类型的。 ...

图片转为base64

// 图片转化成base64字符串
public static string getimagestr() {// 将图片文件转化为字节数组字符串,并对其进行base64编码处理
    string imgfile = "c:/image1/2.png";// 待处理的图片
    inputstream in = null;
    byte[] data = null;
    // 读取图片字节数组
    try {
        in = new fileinputstream(imgfile);
        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) { // 对字节数组字符串进行base64解码并生成图片
    if (imgstr == null) // 图像数据为空
        return false;
    base64decoder decoder = new base64decoder();
    try {
        // base64解码
        string basevalue = imgstr.replaceall(" ", "+");//前台在用ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
        string s = basevalue.replaceall("data(.*?);base64,","");
        byte[] b = decoder.decodebuffer(s);
        imgstr = imgstr.replace("base64,", "");
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// 调整异常数据
                b[i] += 256;
            }
        }
        // 生成jpeg图片
        outputstream out = new fileoutputstream(imgfilepath);
        out.write(b);
        out.flush();
        out.close();
        return true;
    } catch (exception e) {
        return false;
    }
}

 这里在转码时,使用正则表达式自动甄别图片是什么类型的。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网