【问题标题】:Converting a byte[] to a Bitmap将 byte[] 转换为 Bitmap
【发布时间】:2015-01-05 20:57:16
【问题描述】:

我正在尝试将图像 (BLOB) 的 64 位编码字符串转换为位图,以便可以在图像视图上显示它。 64 位解码的代码工作正常并返回 byte-stream ,但将返回的 byte-stream 转换为 Bitmap 会返回 null 。 请帮忙。

//This statement works
byte[] decodedString = Base64.decode(c.getString(TAG_PICTURE).toString().getBytes(),
Base64.DEFAULT);

//This statement returns null
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

完整代码如下:-

try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Getting JSON Array node
            products = jsonObj.getJSONArray(TAG_PRODUCTS);

            // looping through All Contacts
            for (int i = 0; i < products.length(); i++) {
                JSONObject c = products.getJSONObject(i);     
                Double prod_price =  Double.valueOf(c.getString(TAG_PRICE));

                //The code below works as it returns the byte-array
                 byte[] decodedString = Base64.decode(c.getString(TAG_PICTURE), Base64.DEFAULT);

                //The code below returns null even though the byte-stream is known 
                //from  above
                Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, 
                decodedString.length);

                myProductsList.add(new PRODUCT(c.getString(TAG_PRODUCT_NAME),c.getString(TAG_STORE_NAME), c.getString(TAG_OWNER_NAME), c.getString(TAG_DESCRIPTION), prod_price,bitmap));


            }
        } catch (JSONException e) {
            e.printStackTrace();
   }

我很感激这个问题的解决方案,因为我花了很长时间搜索,现在被困在这个问题上。
提前致谢。

【问题讨论】:

    标签: android imageview base64 bytearray blob


    【解决方案1】:

    更改此代码:

    byte[] decodedString = Base64.decode(c.getString(TAG_PICTURE).toString().getBytes(), Base64.DEFAULT);
    

    收件人:

    byte[] decodedString = Base64.decode(c.getString(TAG_PICTURE), Base64.DEFAULT);
    

    没有必要调用toString,因为你已经使用getString,并且不要调用getBytes,只需将编码 String 传递给decode 1st param

    【讨论】:

    • 感谢@Blaze Tama 的建议,我试过了,还是不行。我重新编辑了帖子以适应你的建议。
    • 欢迎您 :) 您确定 c.getString(TAG_PICTURE) 返回 base64 编码的字符串吗?我使用此代码(我的答案),它工作正常
    • 是的,decodedString 变量总共有 65535 个字节。
    • 之前在数据库服务器上通过PHP语句进行编码:$product["picture"]=base64_encode($row["picture"]);调试代码时能够看到 base64 编码流。
    【解决方案2】:

    感谢所有提出建议的人。我发现根本问题不在于 Java 编程方面,而在于数据库。我一直将图像存储为 blob 数据类型,这对于图像来说往往很小。将数据类型更改为 mediumblob 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2012-06-09
      • 1970-01-01
      • 2011-06-08
      • 2013-02-23
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多