How to convert base64 string to image binary file

2019-04-02 07:47发布

This question already has an answer here:

As an example I have converted a canvas element with a re-sized image and posted into a hidden input field that's now encoded as

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...

This value then posted to the same page which I need to convert this string into an image and save onto the server.

Code Behind File (upload.aspx)

protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile filePosted = Request.Files["newinput"];
        string base64String = filePosted.ToString();

            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);

//I DONT KNOW HOW TO WRITE ABOVE INTO THE SaveAs CONDITION BELOW


        if (filePosted != null && filePosted.ContentLength > 0)
        {
            string fileNameApplication = Path.GetFileName(filePosted.FileName);
            string fileExtensionApplication = Path.GetExtension(fileNameApplication);

            // generating a random guid for a new file at server for the uploaded file
            string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
            // getting a valid server path to save
            string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);

            if (fileNameApplication != String.Empty)
            {
                filePosted.SaveAs(filePath);
            }

        }

I'm pretty sure I need to convert this the imagedata to a binary file before saving on the server but I can't quite get how I need to amend the code above. Any ideas? The code to save to the server doesn't work.

Once I have converted this to an image and changed it's name as above - I'm storing this back to a database via LINQ - with a URL appended to it.

Any help would be greatly appreciated.

1条回答
forever°为你锁心
2楼-- · 2019-04-02 08:29

Hope below functions helps.

public string ImageToBase64(Image image,
          System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

        public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }

EDIT 1 -

From the comments it seems that you are getting base64 string and you need to save it as image on server and then whenever required you need to show that image using physical server path.

Ok. Base64ToImage will give you image for your base64 string. You can save it on server using

image.Save("PATH", System.Drawing.Imaging.ImageFormat.Jpeg);

And this "PATH" you have supplied or created can be stored in DB as URL, which you can use at the time of display.

Note: Make sure that you have write access to folder where you are saving image.

EDIT-2 Your function should look like below. Please put validation code, error handling as required.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile filePosted = Request.Files["newinput"];
        string base64String = filePosted.ToString();

            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image   = System.Drawing.Image.FromStream(ms, true);
            string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
            string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);
            image.Save(filepath,ImageFormat.Jpeg);
   }
查看更多
登录 后发表回答