// 将网络图片转成Base64码, 此方法可以解决解码后图片显示不完整的问题
public static String imgBase64(String imgURL) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024];
try {
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "fail";//连接失败/链接失效/图片不存在
}
InputStream inStream = conn.getInputStream();
int len = -1;
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}
//获取网络上的图片,转换为InputStream
public static InputStream getImageStream(String url) {
System.out.println("url======= " + url);
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
System.out.println("获取网络图片出现异常,图片路径为:" + url);
e.printStackTrace();
}
return null;
}
//将网络地址对应的图片转换为base64
public static String imageChangeBase64(String imagePath){
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024];
try {
// 创建URL
URL url = new URL(imagePath);
// 创建链接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
if(conn.getResponseCode() != sun.net.www.protocol.http.HttpURLConnection.HTTP_OK) {
return "fail";//连接失败/链接失效/图片不存在
}
InputStream inStream = conn.getInputStream();
int len = -1;
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}
/**
* @Description: 图片转化成base64字符串
* @param: path
* @Return:
*/
public static String GetImageStr(String path) {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
//待处理的图片
String imgFile = path;
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);
// base64编码后进行urlencode
// java.net.URLEncoder.encode(string, "GBK")
}