Translate

Wednesday, June 11, 2025

Converting a System.IO.MemoryStream object to Image in Dynamics 365 Finance and Operations using x++

๐Ÿ“˜ Introduction

In Dynamics 365 Finance and Operations (D365FO), it's common to deal with external systems returning image streams, such as a barcode service, a document API, or a file server. In such cases, you may receive the image as a binary stream (System.IO.Stream), You’ll need to convert it into a container to display it in the UI or store it in the database.

This blog post explains how to convert a MemoryStream into a displayable image in D365FO using X++.

๐Ÿงช Sample Scenario

Let’s say you're calling an external URL using System.Net.HttpWebRequest and want to load the image from the response into a form control.

✅ X++ Code to Convert MemoryStream to Image

System.Net.HttpWebRequest request = System.Net.WebRequest::Create("https://example.com/sample-image.png") as System.Net.HttpWebRequest;

System.Net.HttpWebResponse response;
System.IO.Stream stream;
System.IO.MemoryStream fileStream = new System.IO.MemoryStream();

request.Method = "GET";
request.ContentType = "image/png";

response = request.GetResponse() as System.Net.HttpWebResponse;

using (response)
{
    stream = response.GetResponseStream();

    // Convert the stream into a memory stream
    stream.CopyTo(fileStream);

    // Convert memory stream to container
    BinData binData = new BinData();
    container baseContainer = Binary::constructFromMemoryStream(fileStream).getContainer();
    Image image = new Image();

     // Set container data to BinData
    binData.setData(baseContainer);

    // Set image data
    image.setData(binData.getData());

     // Display in image control (e.g., FormImageControl1)
    FormImageControl1.image(image);
}


๐Ÿ’ฌ Explanation

  • HttpWebRequest is used to call the external image URL.

  • ✅ The response stream is copied into a MemoryStream.

  • ✅ We use Binary::constructFromMemoryStream() to convert the stream into a container.

  • ✅ This container is then used to create an Image object.

  • ✅ Finally, we bind it to the form’s image control like FormImageControl1.

๐Ÿ’ก Use Case Ideas

  • Show customer logos dynamically.

  • Load barcode images from external services.

  • Display product thumbnails received via APIs.

๐Ÿง  Conclusion

Working with external image streams in D365FO using X++ becomes seamless when you properly convert the stream into a container and use BinData + Image objects. This approach is ideal for real-time image rendering from REST APIs or streaming sources.