Breyta

Deila með


Use image column data in Microsoft Dataverse

You can store image data in Microsoft Dataverse using image columns or file columns. Image columns in Dataverse have special behaviors and limitations designed to support displaying images within applications, and you can use many of the same APIs for file columns with image columns.

The following table introduces some of the differences between image and file columns.

Image File
File Size Limited to 30 MB. Up to 10 GB. While the API can handle files up to 10 GB in size, Power Apps client controls currently only support files up to 128 MB. Exceeding the 128 MB value when using these controls will result in errors uploading or downloading files.
File Types Only Image file types All file types allowed by the Organization.BlockedAttachments value. More information: Block certain types of files
Set with Update You can set image column data with other record data using update. You can only upload files individually to file column properties.
Delete with Update You can delete image column data by setting the attribute or property to null and then update the record. More information: Delete images You can only delete file column data using the DeleteFile message or sending a DELETE request to the specific column using Web API. More information: Delete Files
Set with Create When the image column is the primary image, you can set image data with other record data using create. More information: Primary Images You can only upload files individually to file column properties after the record was created.
Return with Retrieve You can retrieve thumb-nail sized images with other record data using retrieve. The value returned is the file ID. More information: Behavior when retrieving
Download URL Each image column has a string column that contains a relative URL you can include in an application that allows downloading the image file. More information: Download URL There's no string column with a download URL, but you can compose a URL to download the file directly from the Web API. More information: Download a file in a single request using Web API

Maximum image size

Just like file columns, you can specify the maximum size of data stored in an image column by using the MaxSizeInKb property. However, the maximum allowed size is 30 MB.

If you try to upload a file that's too large, you get the following error message:

Name: ProcessImageFailure
Code: 0x80072553
Number: -2147015341
Message: Error occured when processing image. Reason: File size is too big. MaxSize: 0 MB, Uploaded filesize: 0 MB.

To check the maximum file size, use the following examples:

The following static GetImageColumnMaxSizeInKb method returns the MaxSizeInKB value for an ImageAttributeMetadata column.

/// <summary>
/// Retrieves the MaxSizeInKb property of an image column.
/// </summary>
/// <param name="service">IOrganizationService</param>
/// <param name="entityLogicalName">The logical name of the table that has the column</param>
/// <param name="imageColumnLogicalName">The logical name of the image column.</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static int GetImageColumnMaxSizeInKb(
   IOrganizationService service, 
   string entityLogicalName, 
   string imageColumnLogicalName) 
{

   RetrieveAttributeRequest retrieveAttributeRequest = new() { 
         EntityLogicalName = entityLogicalName,
         LogicalName = imageColumnLogicalName
   };

   RetrieveAttributeResponse retrieveAttributeResponse;
   try
   {
         retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
   }
   catch (Exception)
   {
         throw;
   }

   if (retrieveAttributeResponse.AttributeMetadata is ImageAttributeMetadata imageColumn)
   {
         return imageColumn.MaxSizeInKB.Value;
   }
   else
   {
         throw new Exception($"{entityLogicalName}.{imageColumnLogicalName} is not a image column.");
   }
}

More information:

Image file types

Image columns store the following binary image types:

File Format MIME type File extensions
Graphics Interchange Format image/gif .gif
Joint Photographic Expert Group image image/jpeg .jpg, .jpeg
Bitmap file image/bmp .bmp
Portable Network Graphics image/png .png

If you try to save a file that isn't one of these types, you get the following error message:

Name: ProcessImageFailure
Code: 0x80072553
Number: -2147015341
Message: Error occured when processing image. Reason: Update image properties failed for objectid: <id of record>, logicalName: <logical name of table>, attribute: <logical name of image column

Full-size and thumbnail-sized images

When you set an image column value, Dataverse automatically generates a thumbnail-sized image that's suitable for use as an icon in an application.

If you configure the image column to store a full-sized image, you can save and download a file up to the configured MaxSizeInKb separately from the thumbnail-sized image. The ImageAttributeMetadata.CanStoreFullImage property controls whether an image column stores a full-sized image.

Detect which image columns support full-sized images

You can query the Image Attribute Configuration (AttributeImageConfig) table to retrieve a list of image columns that support full-sized images by using the parententitylogicalname, attributelogicalname, and canstorefullimage column values.

The static PrintFullSizedImageColumns method writes the names of the table and image columns that can store full-sized images.

static void PrintFullSizedImageColumns(IOrganizationService service)
{
    QueryExpression query = new QueryExpression("attributeimageconfig")
    {
        ColumnSet = new ColumnSet("parententitylogicalname", "attributelogicalname"),
        Criteria = new FilterExpression(LogicalOperator.And)
        {
            Conditions =
            {
                new ConditionExpression(
                    attributeName: "canstorefullimage",
                    conditionOperator: ConditionOperator.Equal,
                    value: true)
            }
        }
    };

    EntityCollection response = service.RetrieveMultiple(query);
    foreach (Entity record in response.Entities)
    {
        Console.WriteLine($"{record["parententitylogicalname"]}.{record["attributelogicalname"]}");
    }
}

Output

account.sample_sampleimage

You can also query schema definitions to return columns where the ImageAttributeMetadata.CanStoreFullImage property is true. For more information, see Query schema definitions.

Resize rules for thumbnail-sized images

To generate a thumbnail-sized image, Dataverse crops and resizes the image to a square shape according to the following rules:

  • If at least one side of the image is larger than 144 pixels, Dataverse crops the image on center to 144x144 pixels.
  • If both sides of the image are smaller than 144 pixels, Dataverse crops the image square to the smallest side.

The following table shows two examples.

Before After
Image before resize

300x428
image after resize

144x144
smaller image resize before

91x130
smaller image resize after

91x91

Primary images

Each table can have multiple image columns, but you can only define one image column as the primary image. You can only set the primary image by using a create operation. For more information, see Set only primary images for create operation.

The ImageAttributeMetadata.IsPrimaryImage property controls which image column represents the primary image for the table.

The EntityMetadata.PrimaryImageAttribute property returns the logical name of the image column that is the current primary image for the table.

You can also query the Entity Image Configuration (EntityImageConfig) table to determine which image columns represent the current primary image by using the parententitylogicalname and primaryimageattribute column values.

The static PrintPrimaryImageColumns method in the following example writes the table and image column names for all primary image columns.

static void PrintPrimaryImageColumns(IOrganizationService service)
{
    QueryExpression query = new QueryExpression("entityimageconfig")
    {
        ColumnSet = new ColumnSet("parententitylogicalname", "primaryimageattribute"),
    };

    EntityCollection response = service.RetrieveMultiple(query);
    foreach (Entity record in response.Entities)
    {
        Console.WriteLine($"{record["parententitylogicalname"]}.{record["primaryimageattribute"]}");
    }
}

Output

account.sample_sampleimage

More information: Build queries with QueryExpression

Download URL

Each image column has the following companion columns, but none of them appear within the Power Apps designer.

Column Type Naming convention Description
Image ID Unique identifier <image column name>Id A unique identifier for the image.
Time Stamp BigInt <image column name>_Timestamp Represents when the image was last updated. This value helps make sure the latest version of the image is downloaded rather than the client using a cached version that was retrieved before.
URL string <image column name>_URL A relative URL to download a thumbnail-sized version of the image

The image ID and time stamp column values don't have any use cases except that they're used to within the URL string column value.

When the column for a record contains data, the download URL is a relative URL that uses the following format:

/Image/download.aspx?Entity=<entity logical name>&Attribute=<image column logical name>&Id=<image id value>&Timestamp=<time stamp value>

You can append this value to the organization URI to construct a URL that you can use to download the thumbnail-sized image file. For example:

https://yourorg.crm.dynamics.com/Image/download.aspx?Entity=account&Attribute=sample_imagecolumn&Id=7a4814f9-b0b8-ea11-a812-000d3a122b89&Timestamp=637388308718090885

URL to download full-sized image

If the image column is configured to store full-sized images, you can append &Full=true to the URL and the link downloads the full-sized image. For example:

https://yourorg.crm.dynamics.com/Image/download.aspx?Entity=account&Attribute=sample_imagecolumn&Id=7a4814f9-b0b8-ea11-a812-000d3a122b89&Timestamp=637388308718090885&Full=true

If the column isn't configured to store full-sized images, the request returns no data.

Use image data with records

When you work with records, how you handle image data depends on whether you're using the SDK or Web API.

The following static RetrieveAndUpdateImageColumn method retrieves a byte[] image value from a column, saves it locally, and uploads a new image.

static void RetrieveAndUpdateImageColumn(
    IOrganizationService service,
    Guid accountid,
    string imageColumnLogicalName) 
{

    // Retrieve account with image
    Entity account = service.Retrieve(
        entityName: "account",
        id: accountid, 
        columnSet: new ColumnSet(imageColumnLogicalName));

    // Save the image retrieved
    File.WriteAllBytes(
        path: "original_image.png",
        bytes: account.GetAttributeValue<byte[]>(imageColumnLogicalName));


    // Instantiate a new entity for update with new image
    Entity accountForUpdate = new("account") { 
        Attributes = {
            { "accountid", accountid },
            { imageColumnLogicalName , File.ReadAllBytes("new_image.png")}
        }
    };

    // Update the account
    service.Update(accountForUpdate);               
}

Note

If you set the ColumnSet.AllColumns property to true, the query doesn't include image columns. For performance reasons, you must explicitly specify that you want to retrieve image data.

More information:

Set only primary images for create operation

When you create a record, set only the value of the current primary image column. If you try to set the value of any other image column, you get this error message:

Name: CannotUploadNonPrimaryImageAttributeOnCreate
Code: 0x80090487
Number: -2146892665
Message: Non-primary image attribute <image column logical name> of entity <table logical name> is not allowed to upload during Create operation.

For more information, see Primary Images.

Retrieve only thumbnail images

The image data you access through record properties is always the thumbnail-sized images. To access full-sized images, you must download them. For more information, see Download images.

Upload images

To upload images, use the same APIs you use to upload files. For more information, see Upload Files.

Download images

To download images, use the same APIs you use to download files. Be aware of the following differences.

Using Dataverse messages

If you use the InitializeFileBlocksDownload and DownloadBlock messages, you always download the full-sized image if the image column supports it. You can't download the thumbnail-sized image by using this method. For more information, see Use Dataverse messages to download a file.

If the image column doesn't support full-sized images, or if the ImageAttributeMetadata.CanStoreFullImage property is false when you upload the image, the following error is returned:

Name: ObjectDoesNotExist
Code: 0x80040217
Number: -2147220969
Message: No FileAttachment records found for imagedescriptorId: <guid> for image attribute: <image column logical name> of <entity logical name> record with id <guid>.

Using Web API

When you download images by using the Web API without using the Dataverse messages, you download the thumbnail-sized image by default. To download the full-sized image, append this parameter to the URL: ?size=full.

If the image column doesn't support full-sized images, or if the ImageAttributeMetadata.CanStoreFullImage property is false when you upload the image, the response returns 204 No Content.

For more information, see Download Files.

Delete images

You can delete images by setting the image column value for the record to null as you would for any other property.

Set the value of the image attribute to null and update the entity. For more information, see Basic update.

See also

Files and images overview
Work with image column definitions using code
Sample: Image Operations using Dataverse SDK for .NET
Sample: Image Operations using Dataverse Web API
Use file column data