簡體   English   中英

無法將位圖轉換為字符串,然后使用BitmapFactory.decodeByteArray返回位圖

[英]Unable to convert bitmap to string then back to bitmap using BitmapFactory.decodeByteArray

我將basemap編碼為字符串,以便將其作為JSON對象的一部分發送。 圖像的收件人將獲取字符串並再次將其轉換為圖像。

如果這完全相關,我正在為Android應用程序執行此操作。

將位圖轉換為字符串似乎工作正常,但是當將字符串轉換回位圖時,我得到NullPointerException。

我已經嘗試將其歸結為基礎知識(並轉換為字符串並返回到相同方法中的位圖進行測試),所以我有以下內容:

public static void convertBitmapToBase64String(Context context, String filename, int maxStringSize)
{
    Bitmap originalBmp = PicUtils.getBitmapFromFilename(filename, null, -1);
    String base64Image = PicUtils.convertBitmapToBase64StringFromFile(context, TEMP_FILENAME);

    // The encoded string is not null, so encoding seems to work.
    DataUtils.log("base64Image length is " + base64Image.length());

    // Test if we can convert back
    final byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);

    // This returns null! Is failing here.
    Bitmap decodedByteBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}

public static Bitmap getBitmapFromFilename(String filename)
{
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filename, options);
    Bitmap finalBitmap = BitmapFactory.decodeFile(filename);
    return finalBitmap;
}

public static String convertBitmapToBase64StringFromFile(Context context, String filename)
{
    try {
        FileInputStream fis = context.openFileInput(filename);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Base64OutputStream outputStream = new Base64OutputStream(byteArrayOutputStream, Base64.DEFAULT);
        IOUtils.copy(fis, outputStream);
        return new String(byteArrayOutputStream.toByteArray(),"UTF-8");

    } catch (Exception e) {
        e.printStackTrace();
        DataUtils.log(e.getMessage());
        return null;
    }
}

任何提示表示贊賞!

這是我用來解決問題的鏈接。 我希望這對你也有用。

http://androidtrainningcenter.blogspot.in/2012/03/how-to-convert-string-to-bitmap-and.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM