Android在解码位图时返回null

时间:2017-05-27 18:54:15

标签: android bitmap

我正在编码图像,将它们转换为Base64字符串并将它们保存在数据库中,但是当我尝试解码字符串并将其转换回位图时,它将返回null:

以下是我在解码过程中使用的代码:

private Bitmap decodeFile(String encod){
        Bitmap b = null;
        byte[] temp=null;
        temp = Base64.decode(encod, Base64.DEFAULT);
        ByteArrayInputStream imageStream = new ByteArrayInputStream(
                temp);
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(imageStream, null, o);
        int scale = 1;
        if (o.outHeight > 500 || o.outWidth > 500) {
            scale = (int)Math.pow(2, (int) Math.ceil(Math.log(500 /
                    (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }
        BitmapFactory.Options o1 = new BitmapFactory.Options();
        o1.inSampleSize = scale;
        b = BitmapFactory.decodeStream(imageStream, null, o1);
        return b;
    }

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您正在使用ByteArrayInputStream两次而不重置缓冲区位置。

在第二次使用imageStream.reset();之前尝试使用decodeStream

        imageStream.reset();
        b = BitmapFactory.decodeStream(imageStream, null, o1);
  

ByteArrayInputStream reset():

     

将缓冲区重置为标记的   位置。

答案 1 :(得分:0)

相反,您可以使用更简单的方法解码编码图像,如下所示:

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