【问题标题】:Why is my BitmapFactory.decodeByteArray returning null?为什么我的 BitmapFactory.decodeByteArray 返回 null?
【发布时间】:2015-07-21 12:04:26
【问题描述】:

我正在尝试将存储在数据库中的 Base64 格式的图像转换为要在 Imageview 中使用的位图。

所以,我以这种方式将其存储在 SQLite 中:

Bitmap imageBitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap fotoGrande=(Bitmap) extras.get("data");
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
//I am adding some data to EXIF here, add to an static ArrayList<Bitmap> in other class and I store it this way:

int bytes=listaFotos.get(i).getFoto().getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
listaFotos.get(i).getFoto().copyPixelsToBuffer(buffer);
values.put("foto", Base64.encodeToString(buffer.array(), Base64.DEFAULT));

稍后,我需要将该图像放入 ImageView 中:

String foto = csr2.getString(0);//csr2 is a cursor
byte[] arrayFoto = Base64.decode(foto, Base64.DEFAULT);//This is not null
Bitmap fotoBitmap = BitmapFactory.decodeByteArray(arrayFoto, 0, arrayFoto.length);//This is null

我知道有很多关于此的问题。我搜索了,但没有答案解决我的问题。

为什么我的 BitmapFactory.decodeByteArray 返回 null?我做错了什么?有什么帮助吗?

谢谢。

【问题讨论】:

  • 如果图像无法解码,则返回 null。
  • 是的,我知道,我读了文档,我想知道为什么图像无法解码。
  • 可能是因为这样做的内存用完了。拍摄一个非常小的图像,您会看到它已解码。

标签: android android-bitmap


【解决方案1】:

原来是数据库问题。 SQLite 为您提供 1MB MAX 大小的游标。我正在从数据库中获取字节,光标大小为 1MB,图片未正确发送。

为了解决这个问题,我将照片的路径而不是字节存储在数据库中。

【讨论】:

    【解决方案2】:

    首先图像在Bitmap 中转换为String 像这样

     ByteArrayOutputStream stream = new ByteArrayOutputStream();
            camera.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte imageInByte[] = stream.toByteArray();
            String encodedImage = Base64.encodeToString(imageInByte, Base64.DEFAULT);
    

    其中camera 是位图。 并将字符串encodedImage 存储在数据库中

    和getImage这样的字符串

     byte[] b = Base64.decode(encodedImage , Base64.DEFAULT);
            Bitmap  bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    

    【讨论】:

    • 或多或少……我正在做同样的事情。无论如何,我的问题是当我从数据库接收数据时,而不是当我存储它时。我保存它没有任何问题。
    • 然后检查数据库数据中获取的数据何时不为空。
    • 然后检查一些其他问题,因为这段代码运行并返回位图成功。
    • 这就是我生气的原因,该代码应该可以工作......我在存储到数据库之前将其压缩为 JPEG。也许我应该“解压”它?我认为 Android 支持 JPEG,但也许我必须将其转换为常规位图...?
    • 请检查您何时将图像存储在数据库中.. 因为您以正确的方式获取图像..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-06-06
    相关资源
    最近更新 更多