我正在尝试将图像下载到字节数组中,但它给了我一条错误消息,
我该怎么办?请大家帮帮我
05-29 12:28:13.324: D/ImageManager(6527): Error: java.lang.IllegalArgumentException: Buffer capacity may not be negative
byte []bg1=getLogoImage("http://onlinemarketingdubai.com/hotelmenu/images/874049310_gm.png");
private byte[] getLogoImage(String url){
try {
Log.d("Url",url);
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
HttpURLConnection conn= (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(length);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
最佳答案
看一下 ByteArrayBuffer
类:
public final class ByteArrayBuffer {
private byte[] buffer;
private int len;
public ByteArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
您正在初始化它,并将 length
值传递给它,作为您从中获取的缓冲区的capacity
:
int length = conn.getContentLength();
所以问题来自于连接长度,我认为它是-1,因为内容长度未知。服务器可能没有在响应消息中设置“Content-Length” header 。
看看这个 answer来解决这个问题。
关于java - 尝试从 url 下载图像时,出现缓冲区容量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16807520/