0

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

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

但是,我被困在某个地方:null当我从 bytearray 解码时,我得到了

我使用的代码是:

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);

但我收到错误:

位图位图为空。

4

1 回答 1

0

Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.

So, You can do like this way, Encode - Decode,

Encode the image before writing to the database:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray();  // write this to database as blob

And then decode it like the from Cursor:

ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);

Also, If this not work in your case, then I suggest you to go on feasible way..

  • Make a directory on external / internal storage for your application images.
  • Now store images on that directory.
  • And store the path of those image files in your database. So you don't have a problem on encoding-decoding of images.
于 2012-06-30T10:36:19.337 回答