您的位置:首页 > 其它

用到了base64转图片文件的函数,记录一下

2016-08-16 14:20 323 查看
import java.io.*;
import sun.misc.*;

//对图片文件进行Base64编码
public String getImagebase64(String imgFileName) {
byte[] data = null;
try {
InputStream in = new FileInputStream(imgFileName);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}

BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}

//Base64解码并保存图片文件
public void saveImage(String base64, String imgFileName) {
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFileName);
out.write(bytes);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
具体来说是因为这个原因:前端使用某个richEditor控件,当粘贴图片时会自动以base64数据的格式存放,考虑到直接存进数据库一来会有性能问题,二来会有字段长度问题,所以先把这些base64数据提取出来,保存成文件,再用文件路径替换img src=""中的内容,即可达到目的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐