Επεξεργασία

Κοινή χρήση μέσω


Use image column data

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

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 using the MaxSizeInKb property. However the maximum allowed size is 30 MB.

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

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.

You can use the following examples to check the maximum file size:

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 extension(s)
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'll get the following error:

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 an image column value is set, Dataverse will automatically generate a thumbnail-sized image that is suitable for use as an icon in an application.

If the image column is configured to store a full-sized image, a file up to the configured MaxSizeInKb can be saved and downloaded separately from the thumbnail-sized image. The ImageAttributeMetadata.CanStoreFullImage property controls whether an image column will store 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 using the parententitylogicalname, attributelogicalname, and canstorefullimage column values.

The static PrintFullSizedImageColumns method will write 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 ImageAttributeMetadata.CanStoreFullImage property is true. More information: Query schema definitions

Resize rules for thumbnail-sized images

To generate a thumbnail-sized image, Dataverse will crop and resize the image to a square shape according to the following rules:

  • Images with at least one side larger than 144 pixels are cropped on center to 144x144.
  • Images with both sides smaller than 144 are cropped square to their 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 only one image column can be defined as the primary image. Only the primary image can be set with a create operation. More information: Only primary images can be set for create

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 using the parententitylogicalname and primaryimageattribute column values.

The static PrintPrimaryImageColumns method below will write the table and image column names of 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 will be a relative URL using 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 can be used 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 will download 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, no data will be returned.

Use image data with records

When you're working with records, how you work with 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

Image columns are not included if you set the ColumnSet.AllColumns property to true. For performance reasons you must explicitly specify that you want to retrieve image data.

More information:

Only primary images can be set for create

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

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.

More information: Primary Images

Only thumbnail images can be retrieved

The image data you access via record properties will always be the thumbnail-sized images. To access full-sized images, you must download them. More information: Download images

Upload images

Use the same APIs you use to upload files to upload images individually. More information: Upload Files

Download images

Use the same APIs you use to download files to download images, but be aware of the following differences.

Using Dataverse messages

If you use the InitializeFileBlocksDownload and DownloadBlock messages, the full-sized image will always be downloaded if the image column supports them. You can't download the thumbnail-sized image using this method. More information: Use Dataverse messages to download a file

If the image column doesn't support full-sized images, or if the ImageAttributeMetadata.CanStoreFullImage property was false when the image was uploaded, 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 using the Web API without using the Dataverse messages, the thumbnail-sized image will be downloaded by default. To download the full-sized image, you must append this parameter to the URL: ?size=full.

If the image column doesn't support full-sized images, or if the ImageAttributeMetadata.CanStoreFullImage property was false when the image was uploaded, the response will return 204 No Content.

More information: 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.

Simply set the value of the image attribute to null and update the entity. More information: 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