首页 文章

Android在解码位图时返回null

提问于
浏览
1

我正在编码图像,将它们转换为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 回答

  • 1

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

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

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

    ByteArrayInputStream reset():将缓冲区重置为标记位置 .

  • 0

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

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

相关问题