解码Base64图像

时间:2011-02-22 20:08:50

标签: c# base64 decode

我在嵌入式HTML中有一个Base64图像,如何使用C#或VB.net对其进行解码。

5 个答案:

答案 0 :(得分:27)

google.com> base64图像解码c#> 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(); 
}

答案 1 :(得分:10)

使用Convert.FromBase64String获取代表图像二进制文件的byte[]

然后,您可以将生成的byte[]保存到文件中。

答案 2 :(得分:1)

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

答案 3 :(得分:1)

在上面的示例中,内存流尚未处理这可能会导致内存泄漏。所以基本思路是转换为 base64string到bytearray []到图像或位图图像创建可以通过内存流完成 一个完美的例子 试试这个链接 http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

答案 4 :(得分: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;
    }
}