开发者

Decoding Base64 Image

I have got开发者_如何学C a Base64 image in an HTML embedded, how can I decode this using C# or VB.net.


google.com > base64 image decode 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(); 
}


Use Convert.FromBase64String to get a byte[] representing the image binary.

You can then save the resulting byte[] into a file.


Scrape the embedded image into a string. Using WebClient is probably your best bet. Convert the base64 string to a byte array using Convert.FromBase64String(). Use a MemoryStream and Image.FromStream() to reconstitute an image object.


In above example memory stream has not been disposing This may cause memory leak.So Basic Idea is convertion to base64string to bytearray[] to image or bitmap Image creation can be done through memorystream A perfect example for you Try this link http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx


Here is my Solution, maybe its helpful:

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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜