Reputation: 335
I want to save a base64 string as an image into a folder on server and database using C#. But I am getting 'A generic error occurred in GDI+.' Can someone tell me what is wrong with this code?
My Controller:
public ActionResult ShareProduct(Product item, PhotoProduct prphoto, string[] Photo)
{
foreach (string file in Photo)
{
if (file != null)
{
string base64 = file.Substring(file.IndexOf(',') + 1);
base64 = base64.Trim('\0');
byte[] imageBytes = Convert.FromBase64String(base64);
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
string newPhoto = Guid.NewGuid().ToString() + ".png";
var path = Path.Combine(Server.MapPath("~/Uploads/"));
image.Save("~/Uploads/" + newPhoto);
prphoto.ImageName = "/Uploads/" + newPhoto;
}
}
}
Debug result:
Upvotes: 0
Views: 2194
Reputation: 335
I solved it by changing the code like below. But I'm not sure if it's safe. It works fine for now.
string base64 = file.Substring(file.IndexOf(',') + 1);
base64 = base64.Trim('\0');
string fileName = Guid.NewGuid().ToString() + ".Jpeg";
byte[] imageBytes = Convert.FromBase64String(base64);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
image.Save(Server.MapPath("~/Uploads/"+fileName),
System.Drawing.Imaging.ImageFormat.Png);
prphoto.ImageName = "/Uploads/" + fileName;
Upvotes: -1