0

When i try to convert a base64string to an Image in C#, I'm getting output as "System.Drawing.Bitmap" instead of the actual Image:

Click for Image

public Image DownFile(string base64String)//string file { //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); image.Save("E:/Project Utilitie Connection/FileDownloadTask/Images", System.Drawing.Imaging.ImageFormat.Jpeg); return image; } 
3

2 Answers 2

0

try a using statement for the MemoryStream, like so:

 byte[] bytes = Convert.FromBase64String(base64String); Image image; using (MemoryStream ms = new MemoryStream(bytes)) { image = Image.FromStream(ms); } return image; 
Sign up to request clarification or add additional context in comments.

2 Comments

Still the same old output no change.
I couldn't able to return the image but gave a path to download the image using (Image img = Image.FromStream(new MemoryStream(imageBytes))) { img.Save("Path with filename and extension ", ImageFormat.Jpeg); return img; }
0

The framework is converting the Image object to string which is why you are seeing System.Drawig.Bitmap

Create a response, giving it the bytes from the converted base64 string and then setting the content type for response so the client will know how to render the content.

public class ValuesController : ApiController { [HttpGet] public IHttpActionResult DownFile(string base64String) { if (!string.IsNullOrWhiteSpace(base64String)) { byte[] imageBytes = Convert.FromBase64String(base64String); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(imageBytes); response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); return ResponseMessage(response); } return BadRequest(); } } 

This is a very simplified example to demonstrate how it can be done. Take some time to review and understand what was done so that it can be implemented into your particular scenario.

2 Comments

when i run it using browser it is showing error Error : The resource cannot be found Image Link
Change the URL to api/controller but showing some exception Click for Image

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.