1
嘗試將base64字符串轉換爲字節數組時,出現異常。我將圖像轉換爲字節數組,然後轉換爲base64字符串,然後對其進行加密並將其存儲在文件中。然後我試圖將Base64字符串轉換回MemoryStream中的一個字節數組,並重新創建圖像。我在這裏得到一個出現FormatException:將Base64字符串轉換爲字節時的FormatException
byte[] imgBytes = Convert.FromBase64String(str);
下面是兩個主要功能的完整代碼:
public string ImageToString(Image img)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
return Convert.ToBase64String(ms.ToArray());
}
}
public Image StringToImage(String str)
{
int lent = str.Length;
byte[] imgBytes = Convert.FromBase64String(str);
MemoryStream ms = new MemoryStream(imgBytes, 0, imgBytes.Length);
ms.Write(imgBytes, 0, imgBytes.Length);
return Image.FromStream(ms, true);
}
這裏是BASE64字符串我試圖轉換的開始和結束... 。 G>/9j/4AAQSkZJRgABAQEAYABgAAD .... Uh+8fxpT/B9KAP/2Q==
任何想法,非常感謝!
阿好,我想通了..我是存儲XML樣式文件中的Base64字符串,我加密。在我的代碼之間拉出XML標籤之間的數據,我沒有正確指定起始位置。這是拉動所有正確的數據,包括起始標籤的最後2個字符。在這種情況下,'G>'。謝謝您的幫助! – gwin003