How to convert an object that receives an image in bytes into an actual image?

I am developing a smart device application in C #. In this I call web services. The web service method returns a google map. The return type of the method is an object. The object contains an image in byte format. The object encodes the image in base64 binary format. I need to display the actual image in my application. What type of casting do I need to render the image. Can you provide me with a code or any link through which I can solve the above problem?

+4
source share
2 answers

You can put byte [] in a MemoryStream to create an image, as shown below.

byte[] yourImage; MemoryStream ms = new MemoryStream(image); Image.FromStream(ms); 
+2
source

If you have a string in which the image bytes are really base64 encoded , then you want to call the static FromBase64String method in the Convert class to get an array of bytes:

 byte[] bytes = Convert.FromBase64String("base 64 string"); 

From there you want to create a new instance of MemoryStream with bytes:

 MemoryStream ms = new MemoryStream(bytes); 

Finally, the last call you make is the FromStream static method in the Image class , to get an Image you can work with:

 Image image = Image.FromStream(ms); 

Please note that in the "Notes" section for documentation on the FromStream method in the "Image" class, you must save the Stream instance (from which it comes from MemoryStream) while you use the image.

Also note that although the MemoryStream implementation does not use unmanaged resources and does not necessarily require a Dispose call, this is encoding from the implementation details, as opposed to the contract details that are defined by the Stream class, which indicates that you should call Dispose when you're done with him.

The reason you want to do this is because Stream for the image is another subclass. For example, if you are using an instance of FileStream , you should call Dispose on it when you are done with it (along with the Dispose method on the Image class).

+5
source

Source: https://habr.com/ru/post/1302569/


All Articles