Dynamics Search Engine

Thursday, July 7, 2016

How to export import images or pictures from a table field by X++ code in Microsoft Dynamics AX 2012.

How to export / import a picture or image from a table field by X++ code in Microsoft Dynamics AX 2012.


Applied on: Dynamics AX 2012 R3 CU9.
Prerequisite: Basic Dynamics AX 2012 programming knowledge.
Target audience: AX programmers.Assumption: You are familiar with Dynamics AX 2012.


Below X++ job will explain you how to export an image or picture from Dynamics AX 2012 table. It's a simple piece of code but sometimes we spent hours to get the code how to export picture or image. I have posted here just to make it handy.


static void exportImageFromTable(Args _args)
{
    bindata             bin = new bindata();
    str                 content;
    container           image;
    RetailImages        retailImages;
    FilePath            filepath;
   
   
    select retailImages where retailImages.PictureId == 8045;
   
    filepath = strFmt('C:\\Users\\Administrator\\AppData\\Local\\Temp\\images\\PictureID_%1.jpg', retailImages.PictureId);
    image = retailImages.picture;
    bin.setData(image);
   
    // Create the base64 encoded string
    // content = bin.base64Encode();
    // info(content);
   
    // Save it to the file system as a jpg, png or tif format
    AifUtil::saveBase64ToFile(@filepath, content);
   
}


In addition I am share the code how to import or insert a picture or image in Dynamics AX 2012 using X++ code.

Here is the job:

static void InsertImageToTableField(Args _args)
{
   
    Bindata         binData = new BinData();
    FilePath        path;
    RetailImages    retailImages;
    str             imageID;
   
    path = "C:\\Users\\Administrator\\AppData\\Local\\Temp\\Images\\PictureID_8046.jpg"; // file location
   
    binData.loadFile(path);
   
    select retailImages where retailImages.PictureId == 1111;
   
    if (!retailImages)
    {
        retailImages.picture    = binData.getData();
        retailImages.PictureId  = 1111;
        retailImages.doInsert();
    }
   
}


Hope this was useful. You may leave your comment below.