Base64 字符串轉圖片 問題整理匯總


前言

最近碰到了一些base64字符串轉圖片的開發任務,開始覺得沒啥難度,但隨着開發的進展還是發現有些東西需要記錄下。

Base64 轉二進制

這個在net有現有方法調用:

Convert.FromBase64String(str);

 但在這一步發現調用時就報錯了:Additional information: Base-64 字符數組或字符串的長度無效。

 網上搜索下才發現要轉換的Base64字符串應該為4的整數,如果不是的話要在字符串的末端加上‘=’將其補全為4的整數。

int mod4 = str.Length % 4;
if (mod4 > 0)
{
    str += new string('=', 4 - mod4);
}

 原生二進制數據轉圖片

現在通過Base64的轉換我們有了圖片的二進制數據,一開始就簡單通過以下代碼轉換為圖片:

Image image = Image.FromStream(new MemoryStream(byte));

 但可惜的是,這一步也報錯了,這里大概就猜到應該是我們的二進制數據沒有包含頭部信息,這樣就導致轉換無法繼續。

 所以最后的解決方案如下:

public Bitmap CopyDataToBitmap(int width,int height,byte[] data)
{
    //Here create the Bitmap to the know height, width and format
    Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);

    //Create a BitmapData and Lock all pixels to be written 
    BitmapData bmpData = bmp.LockBits(
                            new Rectangle(0, 0, bmp.Width, bmp.Height),
                            ImageLockMode.WriteOnly, bmp.PixelFormat);

    //Copy the data from the byte array into BitmapData.Scan0
    Marshal.Copy(data, 0, bmpData.Scan0, data.Length);


    //Unlock the pixels
    bmp.UnlockBits(bmpData);


    //Return the bitmap 
    return bmp;
}

 總結

以上就是base64字符串轉圖片碰到問題的匯總,這里記錄下,並附帶參考資料,有興趣的同學可以參考下:

參考資料:

http://www.tek-tips.com/viewthread.cfm?qid=1264492

http://stackoverflow.com/questions/742236/how-to-create-a-bmp-file-from-byte-in-c-sharp

http://stackoverflow.com/questions/2925729/invalid-length-for-a-base-64-char-array

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM