public static String GetImageStr(String imgFile) {
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();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
}
public static boolean GenerateImage(String base64str, String savepath) { // 对字节数组字符串进行Base64解码并生成图片
if (base64str == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(base64str);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(savepath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
Base64对图片进行编码解码
最新推荐文章于 2025-09-12 10:10:28 发布
本文介绍了一个用于处理图片文件的方法,包括将图片转换为Base64编码的字符串及从Base64字符串还原图片的功能。通过这些方法,可以方便地在网络中传输图片,并在客户端或服务器端进行图片的生成。
9148

被折叠的 条评论
为什么被折叠?



