converting a base64 string to an image and saving

2019-01-01 12:35发布

问题:

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!

回答1:

Here is an example, you can modify the method to accept a string parameter. Then just save the image object with .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).



回答2:

You can save Base64 directly into file:

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


回答3:

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


回答4:

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\");
        }
    }
}


回答5:

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.



回答6:

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.



回答7:

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.



回答8:

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();
    }
}