我正在开发一个从web服务器获取图像的应用程序。
我需要把这个图像保存在sqlite数据库中。也许它将保存在一个byte[]中;我已经这样做了,将数据类型作为blob,然后从db检索图像并在imageview上显示。
然而,我被困在某个地方:当我从字节数组解码时,我得到的是null。
我使用的代码是:
InputStream is = null;
try {
URL url = null;
url = new URL(http://....);
URLConnection ucon = null;
ucon = url.openConnection();
is = ucon.getInputStream();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer barb = new ByteArrayBuffer(128);
int current = 0;
try {
while ((current = bis.read()) != -1) {
barb.append((byte) current);
} catch (IOException e) {
e.printStackTrace();
}
byte[] imageData = barb.toByteArray();然后我将imageData插入到数据库中。
要检索图像:
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);但我发现了错误:
位图位图正在变为空。
发布于 2012-06-30 10:36:19
有时,当您的byte[]在以blob类型从数据库检索后没有正确解码时,就会发生这种情况。
所以,你可以这样做,编码-解码,
在写入数据库之前对图像进行编码:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob然后像from游标一样解码它:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);另外,如果这在你的情况下行不通,那么我建议你走上可行的道路.
https://stackoverflow.com/questions/11273289
复制相似问题