Tuesday, February 27, 2024

D365FO - Converting a System.IO.MemoryStream object to Image

 Sometimes we need to either generate or download an image from a 3rd party service and want to serve up the image within the UI.


Below is an example on how to convert a MemoryStream Object that was generated from an HttpWebResponse into something that is viewable on screen or can be saved into the data base



 
	 
                using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    stream = response.GetResponseStream();
                    System.IO.MemoryStream filestream = new System.IO.MemoryStream();
                    
                    //we need to convert the main stream to a memory stream in order to access the binary objects
                    stream.CopyTo(filestream);
     
                   
                    BinData binData = new BinData();
                    container baseContainer;
                    Image image = new Image();
                    
                    //convert the memory stream into a container object which can then be converted into a binData object which can then be defined on an image object which can then be displayed to the end user
		    baseContainer =  Binary::constructFromMemoryStream(fileStream).getContainer();

                    binData.setData(baseContainer);
                    image.setData(binData.getData());
                    //define the image control on a form to the image that was generated from the memory stream
		    FormImageControl1.image(image);
                }   

No comments:

Post a Comment