最近遇到图片与base64字符串互相转换甚是头疼啊,把资源分享给大家,愿大家用的好用
话不多说直接上代码:
- 图片转化成base64字符串(不包含 data:image/jpeg;base64, 东西)
//图片转化成base64字符串
//imgFile路径名称 如:“C:\Users\asus\Desktop\qm.png”
public static String GetImageStr(String imgFile) {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
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编码
return Base64.encodeBase64String(data);
}
- base64字符串转化成图片(并保存到本地)
//base64字符串转化成图片
// imgStr 数据库查出来的base64位字符串 需要截取(data:image/jpeg;base64,)
// imgStr.replace("data:image/jpeg;base64,", "");
public static boolean GenerateImage(String imgStr)
{
System.out.print("已经收到了把字节码转化为图片的方法");
//对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{
//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
//System.currentTimeMillis()
String imgFilePath = "C:\\inetpub\\wwwroot\\school_mart.jpg";//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
- 网络图片转换成base64位字符串
/**
* 网络图片转换Base64的方法
*
* @param netImagePath网络图片路径
*/
public static String NetImageToBase64(String netImagePath) {
String strNetImageToBase64 = null;
final ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(netImagePath);
final byte[] by = new byte[1024];
// 创建链接
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
try {
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
strNetImageToBase64 = encoder.encode(data.toByteArray());
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
// ErrorLogUtils.log("NetImageToBase64:"+e.getMessage());
}
return strNetImageToBase64;
} catch (IOException e) {
e.printStackTrace();
// ErrorLogUtils.log("NetImageToBase64:"+e.getMessage());
return "error";
}
}
本人亲测能用,不能用请留言,我会及时回复解答。