How to read/write the image base64string to "App_Data" in Asp.Net core

  • Thread starter Thread starter Ravi kumar14
  • Start date Start date
R

Ravi kumar14

Guest
Can anyone suggest me, how to read/write the Image base64String to the "App_Data" in .Net Core?

I have tried with the below code snippet. But when I open the Image, it shows me as a Invalid image

public IActionResult RenderImage()
{
// Write the image string to Disk
var imageData = "<any image base64String>";
byte[] imageBytes = Convert.FromBase64String(imagePngData);
MemoryStream data = new MemoryStream(imageBytes);
string filePath = _hostingEnvironment.WebRootPath + "\\" +
"App_Data";
using (var reader = new System.IO.StreamReader(data))
{
string contentAsString = reader.ReadToEnd();
byte[] bytes =
System.Text.Encoding.ASCII.GetBytes(contentAsString);
if (System.IO.File.Exists(filePath + "\\ImageTest.png"))
{
System.IO.File.Delete(filePath + "\\ImageTest.png");
}
System.IO.File.WriteAllBytes(filePath + "\\ImageTest.png",
bytes);
reader.Close();
reader.Dispose();
}

// Read and Display the above written image from disk
Bitmap brokenImage = new Bitmap(filePath + "\\ImageTest.png");
byte[] brokenImageData;
using (MemoryStream ms = new MemoryStream())
{
brokenImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
brokenImageData = ms.ToArray();
}

return File(brokenImageData, "image/Jpeg");
}

My Github Repository: RaviKumarGurunathan/ImageSerialization

The full Stacktrace:

ArgumentException: Parameter is not valid.
System.Drawing.Bitmap..ctor(string filename, bool useIcm)
ImageSave.Controllers.HomeController.RenderImage() in
HomeController.cs-

System.IO.File.WriteAllBytes(filePath + "\\ImageTest.png",
bytes);
reader.Close();
reader.Dispose();
}
// Read and Display the above written image from disk
Bitmap brokenImage = new Bitmap(filePath + "\\ImageTest.png");
byte[] brokenImageData;
using (MemoryStream ms = new MemoryStream())
{
brokenImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
brokenImageData = ms.ToArray();
}

lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object
target, object[] parameters)

Continue reading...
 
Back
Top