1

I am dynamically creating controls in c# code of my asp.net website. I want to create a image control and display a image which is derived from byte array got from wcf service. I tried to convert the byte array in to image and save in a location with the following code but it does'nt work. Can any one help me!

 public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
    return returnImage;
}
3

3 Answers 3

5

You're just missing the Save method:

public string byteArrayToImage(byte[] byteArrayIn)
{
  string saveLocation = "<Path to save image to>"; // e.g. c:\mywebsite\image23.png
  MemoryStream ms = new MemoryStream(byteArrayIn);
  System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
  returnImage.Save(saveLocation);
  return saveLocation;
}

Then use Server.MapPath to pass the url of the saved file location to an asp:Image control.

I should just mention that if you already have a byte array - instead of creating an image object just for saving the bytestream - just put the bytestream inside the ImageUrl of the asp:image control like this:

image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteArrayIn);
Sign up to request clarification or add additional context in comments.

4 Comments

@Annamalai - It should work fine, please show us how you set the URL after receiving the string. Anyways, I added another option for you which doesn't require saving the file to the disk.
Base64 encoded images for data uri's must be on a single line for some browsers. IIRC Convert.ToBase64String split the lines.
In any case, data uri's cannot be cached so this is not recommended due to performance penalty.
@Ken-AbdiasSoftware Haven't encountered any problems with ToBase64String causing line splitting but good to know if that ever comes up. About the performance penalty, saving all the images to the disk (and only storing a string URL in the DB) is always the best practice, but in cases such as OPs - it's not always possible
4

Thats nice. There is no need of creating an image object. This worked for me:

image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteArrayIn);

1 Comment

Prakash, this question is very old. Make sure next time its a active question. GL!
2

Try the following

File.WriteAllBytes(@"C:\test.jpg", BYTE_ARRAY_OF_IMAGE);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.