首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BitmapFactory返回空

BitmapFactory返回空
EN

Stack Overflow用户
提问于 2012-06-30 10:14:47
回答 1查看 368关注 0票数 0

我正在开发一个从web服务器获取图像的应用程序。

我需要把这个图像保存在sqlite数据库中。也许它将保存在一个byte[]中;我已经这样做了,将数据类型作为blob,然后从db检索图像并在imageview上显示。

然而,我被困在某个地方:当我从字节数组解码时,我得到的是null

我使用的代码是:

代码语言:javascript
复制
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插入到数据库中。

要检索图像:

代码语言:javascript
复制
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);

但我发现了错误:

位图位图正在变为空。

EN

回答 1

Stack Overflow用户

发布于 2012-06-30 10:36:19

有时,当您的byte[]在以blob类型从数据库检索后没有正确解码时,就会发生这种情况。

所以,你可以这样做,编码-解码

在写入数据库之前对图像进行编码:

代码语言:javascript
复制
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray();  // write this to database as blob

然后像from游标一样解码它:

代码语言:javascript
复制
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);

另外,如果这在你的情况下行不通,那么我建议你走上可行的道路.

  • 在外部/内部存储中为应用程序映像创建一个目录。
  • 现在将图像存储在该目录上。
  • 并将这些图像文件的路径存储在数据库中。所以你对图像的编码和解码没有问题。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11273289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档