2012-07-23 86 views
8

我试图将一个图像从字节[]转换为位图,以在Android应用程序中显示图像。Android:如何将字节数组转换为位图?

byte []的值由数据库获得,我检查它不是null。 之后,我想转换图像,但不能成功。该程序显示位图的值为空。

我觉得在转换过程中有一些问题。

如果您知道任何提示,请告诉我。

byte[] image = null; 
Bitmap bitmap = null; 
     try { 
      if (rset4 != null) { 
       while (rset4.next()) { 
        image = rset4.getBytes("img"); 
        BitmapFactory.Options options = new BitmapFactory.Options(); 
        bitmap = BitmapFactory.decodeByteArray(image, 0, image.length, options); 
       } 
      } 
      if (bitmap != null) { 
       ImageView researcher_img = (ImageView) findViewById(R.id.researcher_img); 
       researcher_img.setImageBitmap(bitmap); 
       System.out.println("bitmap is not null"); 
      } else { 
       System.out.println("bitmap is null"); 
      } 

     } catch (SQLException e) { 

     } 

回答

6

从你的代码,似乎你把字节数组的一部分,并在部分使用BitmapFactory.decodeByteArray方法。您需要在BitmapFactory.decodeByteArray方法中提供整个字节数组。

从评论

你需要改变你的选择查询(或至少知道有存储在数据库中的图像的BLOB数据列的名称(或指数))编辑。 getByte也使用ResultSet类的getBlob方法。假设列名称是image_data。有了这个信息,更改您的代码是这样的:

byte[] image = null; 
Bitmap bitmap = null; 
    try { 
     if (rset4 != null) { 
       Blob blob = rset4.getBlob("image_data"); //This line gets the image's blob data 
       image = blob.getBytes(0, blob.length); //Convert blob to bytearray 
       BitmapFactory.Options options = new BitmapFactory.Options(); 
       bitmap = BitmapFactory.decodeByteArray(image, 0, image.length, options); //Convert bytearray to bitmap 
     //for performance free the memmory allocated by the bytearray and the blob variable 
     blob.free(); 
     image = null; 
     } 
     if (bitmap != null) { 
      ImageView researcher_img = (ImageView) findViewById(R.id.researcher_img); 
      researcher_img.setImageBitmap(bitmap); 
      System.out.println("bitmap is not null"); 
     } else { 
      System.out.println("bitmap is null"); 
     } 

    } catch (SQLException e) { 

    } 
+0

谢谢您的回复!请让我知道如何在该方法中提供整个字节数组。 – Benben 2012-07-23 14:17:47

+0

你能指定rset4'变量是什么吗?看到你的发布代码,这似乎有你的图像的字节数组。 – Angelo 2012-07-23 14:20:09

+1

OK,rset4是ResultSet的值,用于存储执行SQL的结果。 'ResultSet rset4 = null; rset4 = stmt4.executeQuery(“select * from images where id =”+ id);' – Benben 2012-07-23 14:26:23

12

使用下面一行的字节转换成位图,它是为我工作。

Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length); 

你需要把上面一行外环线的,因为它需要字节数组转换成位图。

P.S. : - 这里imageData是字节数组图片

+0

非常感谢。但现在还不行。我也使用图像的字节数组。 在我的字节数组中有一些问题...? – Benben 2012-07-23 14:19:41

相关问题