// 获取图片并编码
byte[] data = null;
try {
// 创建URL
URL url = new URL(img);//img是图片的地址
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(60 * 1000);
InputStream inStream = conn.getInputStream();
///////////////////////////////////////////////////////////
/*int count = 0;
while (count == 0) {
count = inStream.available();//注意这段注释掉的available方法,这个方法不能保证能全部读取图片的数据信息,所以得到的图片是部分的。此方法不可用
}
data = new byte[count];
inStream.read(data);*/
///////////////////////////////////////////////////////////
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
// 将内容读到b中,读到末尾为-1
while ((len = inStream.read(b)) != -1)
{
// 本例子将每次读到字节数组(buffer变量)内容写到内存缓冲区中,起到保存每次内容的作用
outStream.write(b, 0, len);
}
data = outStream.toByteArray(); // 取内存中保存的数据
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
String imgbase64 = encoder.encode(data);
获取图片 base64编码
最新推荐文章于 2024-12-05 19:15:35 发布