本地图片与网络图片转base64
Posted xiejunna
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了本地图片与网络图片转base64相关的知识,希望对你有一定的参考价值。
package com.test.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
public class ImageToBase64Utils {
/**
* http图片 转base64字符串
* @param imageUrl 超链接
* @return
*/
public static String getBase64ByURLImage(String imageUrl) {
String base64Str = "";
try {
//创建URL对象
URL url = new URL(imageUrl);
//打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时5秒
conn.setConnectTimeout(5 * 1000);
//通过流获取图片数据
InputStream inStream = conn.getInputStream();
//流转byte
byte[] data = getInputStream(inStream);
Base64 base64 = new Base64();
//byte转base64
base64Str = base64.encodeToString(data);
} catch (Exception e) {
e.printStackTrace();
}
return base64Str;
}
private static byte[] getInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,全部读取完毕
int len = 0;
//用输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}
/**
* 从磁盘路径的图片转Base64
*/
public static String getBase64StrByLocalImage(String fileFullName) {
if (fileFullName == null) {
return null;
}
try {
FileInputStream fileInputStream = new FileInputStream(new File(fileFullName));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
for (int n; (n = fileInputStream.read(b)) != -1;) {
byteArrayOutputStream.write(b, 0, n);
}
fileInputStream.close();
byteArrayOutputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
Base64 base64 = new Base64();
return base64.encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
//System.out.println(getBase64ByURLImage("https://www.baidu.com/photo/40112/9407.jpg"));
System.out.println(getBase64StrByLocalImage("F:\\\\E\\\\image\\\\zhongtai\\\\txqw.jpg"));
}
}
以上是关于本地图片与网络图片转base64的主要内容,如果未能解决你的问题,请参考以下文章
JAVA将图片(本地或者网络资源)转为Base64字符串,将base64字符串存储为本地图片