Android:如何将字节数组转换为Bitmap?

Ben*_*ben 10 android bytearray bitmap

我正在尝试将一个图像从byte []转换为Bitmap以在Android应用程序中显示图像.

byte []的值是由数据库得到的,我检查它不是null.在那之后,我想转换图像,但无法成功.该程序显示Bitmap的值为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) {

        }
Run Code Online (Sandbox Code Playgroud)

AAn*_*kit 15

使用下面的行将字节转换为Bitmap,它对我有用.

  Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
Run Code Online (Sandbox Code Playgroud)

你需要将上面的行放在循环之外,因为它需要Bytes Array并转换为Bitmap.

PS: - 这里imageData是 Image的字节数组


Ang*_*elo 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) {

    }
Run Code Online (Sandbox Code Playgroud)