Search code examples
c#asp.netaxaptadynamics-ax-2012business-connector

Converting AxaptaContainer to either Byte[] or Base64


Background: I am trying to display an image from an Ax2012 DB on an ASP.Net page.

Problem: The image is stored in the Ax2012 DB as a BLOB (Or well, an Ax Container). I must to convert this in my C#.Net webservice (Connected via the BusinessConnector) to a Byte array, or even directly to a Base64 string.

What have I done: With the code as below, I get an exception that the imageObject is not serializable. Which I understand to a certain extent, but how else would I do this then?

Code Behind:

while (axRecord.Found)
{
    string workerRecId          = axRecord.get_Field("WorkerRecId").ToString();
    string name                 = axRecord.get_Field("Name").ToString();

    string image;
    using (MemoryStream ms = new MemoryStream())
    {
        AxaptaContainer imageObject = (AxaptaContainer)axRecord.get_Field("Image");
        new BinaryFormatter().Serialize(ms, imageObject);
        image = Convert.ToBase64String(ms.ToArray());
    }

    string wppServiceWarehouse  = axRecord.get_Field("WPPServiceWarehouse").ToString();

    dataTable.Rows.Add(new object[] { workerRecId, name, image, wppServiceWarehouse });
    axRecord.Next();
}

ASP page:

<asp:Image id="employee_ProfilePhoto"   runat="server" imageUrl='<%# "data:image/png;base64," + Eval("Image") %>'/>

I also tried casting it to a string, in which case I get no exception thrown, but also no image ;)

Any advice?

Thanks


Solution

  • You have to convert container to base64 encoded PNG.

    You can add this method to HcmPersonImage (or any orher) table:

    public str getImageAsBase64png()
    {
        Image   imgObj;
        BinData bd;
        str result;
    
        if (this.Image)
        {
            imgObj = new Image(this.Image);
            imgObj.saveType(ImageSaveType::PNG);
    
            bd = new BinData();
            bd.setData(imgObj.getData());
            result = bd.base64Encode();
        }
        else
        {
            result = "";
        }
        return result;
    }
    

    And then call the getImageAsBase64png in .cs code behind:

    axRecord.Call('getImageAsBase64png');