converting a base 64 string to an image and saving it

C#asp.netImage ProcessingBase64

C# Problem Overview


Here is my code:

protected void SaveMyImage_Click(object sender, EventArgs e)
        {
            string imageUrl = Hidden1.Value;
            string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ; 


            HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
            WebResponse imageResponse = imageRequest.GetResponse();

            Stream responseStream = imageResponse.GetResponseStream();

            using (BinaryReader br = new BinaryReader(responseStream))
            {
                imageBytes = br.ReadBytes(500000);
                br.Close();
            }
            responseStream.Close();
            imageResponse.Close();

            FileStream fs = new FileStream(saveLocation, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(imageBytes);
            }
            finally
            {
                fs.Close();
                bw.Close();
            }
        }
}

The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image. I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string. Anybody have some suggestions? Thanks!

C# Solutions


Solution 1 - C#

Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).

public Image LoadImage()
{
    //data:image/gif;base64,
    //this image is a single pixel (black)
    byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }

    return image;
}

It is possible to get an exception A generic error occurred in GDI+. when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).

Solution 2 - C#

You can save Base64 directly into file:

string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));

Solution 3 - C#

Here is what I ended up going with.

    private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
    {
        byte[] bytes = Convert.FromBase64String(base64String);

        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }

        image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
    }

Solution 4 - C#

I would suggest via Bitmap:

public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

Solution 5 - C#

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

Solution 6 - C#

Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:

public void SaveImage()
{
    string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; 

    //this is a simple white background image
    var myfilename= string.Format(@"{0}", Guid.NewGuid());

    //Generate unique filename
    string filepath= "~/UserImages/" + myfilename+ ".jpeg";
    var bytess = Convert.FromBase64String(strm);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

Solution 7 - C#

In a similar scenario what worked for me was the following:

byte[] bytes = Convert.FromBase64String(Base64String);    
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);

ImageTagId is the ID of the ASP image tag.

Solution 8 - C#

If you have a string of binary data which is Base64 encoded, you should be able to do the following:

byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

You should be able to write the resulting array to a file.

Solution 9 - C#

public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
    try
    {
        string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        string filePath = folder + "/" + FileName + "." + FileType;
        File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
        return true;
    }
    catch
    {
        return false;
    }

}

Solution 10 - C#

Using MemoryStream is not a good idea and violates a specification in MSDN for Image.FromStream(), where it says

> You must keep the stream open for the lifetime of the Image.

A better solution is using ImageConverter, e.g:

public Image ConvertBase64ToImage(string base64)
    => (Bitmap)new ImageConverter().ConvertFrom(Convert.FromBase64String(base64));

Solution 11 - C#

In NetCore 6.0, you can use HttpClient and the async methods in the new File class.

The implementation is very simple:

static async Task DownloadFile(string imageUrl, string pathToSave)
{
    var content = await GetUrlContent(url);
    if (content != null)
    {       
        await File.WriteAllBytesAsync(pathToSave, content);
    }
}

static async Task<byte[]?> GetUrlContent(string url)
{
    using (var client = new HttpClient())
    using (var result = await client.GetAsync(url))
        return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}

Usage:

await DownloadFile("https://example.com/image.jpg", @"c:\temp\image.jpg");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanthonypliuView Question on Stackoverflow
Solution 1 - C#CRiceView Answer on Stackoverflow
Solution 2 - C#INT_24hView Answer on Stackoverflow
Solution 3 - C#AustinView Answer on Stackoverflow
Solution 4 - C#Nishant KumarView Answer on Stackoverflow
Solution 5 - C#Milan ShethView Answer on Stackoverflow
Solution 6 - C#Yogesh BhokareView Answer on Stackoverflow
Solution 7 - C#abhishekView Answer on Stackoverflow
Solution 8 - C#afranz409View Answer on Stackoverflow
Solution 9 - C#KHALIDView Answer on Stackoverflow
Solution 10 - C#Mehdi DehghaniView Answer on Stackoverflow
Solution 11 - C#Ester KaufmanView Answer on Stackoverflow