解码 Base64 图像

16

我在HTML中嵌入了一个Base64图像,如何使用C#或VB.net解码它。


http://stackoverflow.com/questions/1915898/base64-decode-in-c-or-java - Tedd Hansen
5个回答

34

如何使用C#对Base64编码的图像进行解码?可以查看此链接:http://www.eggheadcafe.com/community/aspnet/2/39033/convert-base64-string-to-image.aspx

Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));

public string FixBase64ForImage(string Image) { 
    System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image,Image.Length);
    sbText.Replace("\r\n", String.Empty); sbText.Replace(" ", String.Empty); 
    return sbText.ToString(); 
}

7
很好的回答,但是错过了链接中一个重要的函数:public string FixBase64ForImage(string Image) { System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image,Image.Length); sbText.Replace("\r\n", String.Empty); sbText.Replace(" ", String.Empty); return sbText.ToString(); }该函数能够修复图像的base64编码格式,它会去除空格和换行符,返回修复后的字符串。 - Jude Fisher
1
Byte[] bitmapData = new Byte[ImageText.Length]; - 为什么你要分配一个数组,如果你在下一条命令中就要用另一个数组替换它呢? - Spook
现在查询谷歌会将您引导到这里:D - Noman_1

10

使用Convert.FromBase64String方法将图像的二进制数据转换为byte[]类型。

然后,您可以将结果保存到一个文件中。


1

将嵌入的图像抓取到字符串中。使用 WebClient 可能是最好的选择。使用 Convert.FromBase64String() 将 base64 字符串转换为字节数组。使用 MemoryStreamImage.FromStream() 重新构建一个图像对象。


1

0

这是我的解决方案,也许会有帮助:

var lTest12 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAlklEQVQImS3DPwqCUAAH4HeVelG3cHB39hAOLnUAj+BSk4NDXcTNQaLsD7wwbLCCFyiIpObv11AffOK2WSNbzIezaSKdSB7kryi15iPdIw9DXFwXJ8NAKiXFp+9ZVxVfRcEiSZAHAZTjQJAkAL6bhqXWfCqF62o5CP6hbVFGETLPw9GyINB1qOMYd9+Hsm3spjNsR2N+AW4acROELpkYAAAAAElFTkSuQmCC";
Base64Helper
    .Analyze(lTest12)
    .Save2File(new FileInfo(@"C:\tmp\_vvv.ccc"));

public class Base64Helper
{
    public const string SearchToken = "base64,";
    public byte[] DecodedBase64;
    public string FileType;

    private Base64Helper(){}

    /// <summary>
    /// "data:image/jpeg;base64,"
    /// Removes preambleand cleans base64 encoded file content.
    /// Collects the file type if present.
    /// </summary>
    public static Base64Helper Analyze(string pBase64Str)
    {
        var lRet = new Base64Helper();
        var lStringBuilder = new StringBuilder(pBase64Str, pBase64Str.Length);
        lStringBuilder.Replace("\r\n", string.Empty);
        lStringBuilder.Replace(" ", string.Empty);

        var lTokenIndex = lStringBuilder.IndexOf(SearchToken);
        var lSplitIndex = lStringBuilder.IndexOf("/") + 1;
        var lFileTypeLength = lTokenIndex - lSplitIndex - 1;

        if (lSplitIndex > 0 && lFileTypeLength > 0)
            lRet.FileType = lStringBuilder.ToString(lSplitIndex, lFileTypeLength);

        var lStart = lTokenIndex + SearchToken.Length;
        if (lStart > -1)
            lStringBuilder.Remove(0, lStart);

        lRet.DecodedBase64 = Convert.FromBase64String(lStringBuilder.ToString());
        return lRet;
    }

    /// <summary>
    /// Saves the analyzed base64 content to the given file.
    /// if the file type of the base64 is present (default=true)
    /// the file type for the given file will be adjusted accordingly
    /// </summary>
    public void Save2File(FileInfo pSaveToFile, bool pAdjustFileType = true)
    {
        var lFile = pSaveToFile;
        if(pAdjustFileType && string.IsNullOrWhiteSpace(FileType) == false)
            lFile = pSaveToFile.ChangeExtension("." + FileType);

        //FileSystemHelper.EnsureDirectoryExistence(lFile);

        if (lFile.Exists)
            lFile.Delete(); //FileSystemHelper.Delete(lFile);

        using (var lFileStream = lFile.Open(FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
            lFileStream.Write(DecodedBase64, 0, DecodedBase64.Length);
    }

    //Edit: Forgot this here:
    public static int IndexOf(this StringBuilder pThis, string pSearchString, int pStartIndex = 0)
    {
        // Note: This does a StringComparison.Ordinal kind of comparison.
        if (pThis == null)
            throw new ArgumentNullException("pThis");

        if (pSearchString == null)
            pSearchString = string.Empty;

        for (var lIndex = pStartIndex; lIndex < pThis.Length; lIndex++)
        {
            int j;
            for (j = 0; j < pSearchString.Length && lIndex + j < pThis.Length && pThis[lIndex + j] == pSearchString[j]; j++) ;
            if (j == pSearchString.Length)
                return lIndex;
        }

        return -1;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接