我是android的新手,我需要将图像从url保存到db并从db中获取。我将链接转换为字节数组,但收到以下错误:
无法解析ByteArrayBuffer
这是代码:
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
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;
}
答案 0 :(得分:0)
试试这个
Bitmap bm = null;
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
byte[] imageArray = getBytes(bm);
并在此之后使用以下方法
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
return stream.toByteArray();
}
答案 1 :(得分:0)
使用此
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap bitmap = BitmapFactory.decodeFile(url,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
答案 2 :(得分:0)
更新您的方法getLogoImage()
,如下所示。
使用AsyncTask
并从doInBackground()
调用此方法。
这是工作代码。试试这个:
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
}
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}