How to scale and crop images

Looking for an easy method to scale and crop dynamic images? This article explains how to achieve this by setting the image as a background image for a positioned box or table cell. You will explore the effects of the cover and contain settings and learn how utilize the Background settings to crop and scale images.


Setting up the background image

  1. Create a new document and add an image to the Image resources.
  2. Insert an positioned box via the toolbar
  3. Right click the box and choose Box… from the contextual menu (for a table cell this is the Cel… option).
  4. Navigate to the Background tab and select the image as the Source for the Background Image.
  5. Set the Size to contain to preserve the original aspect ratio, but the image is also constrained to not exceed the bounds of the box. Choose cover to preserve the aspect ratio, but the image occupies all the available space (this crops the image). Underwater this is achieved by the background-size CSS property.
  6. Set Position to center center. This centers the image on both the horizontal and vertical axis.

The following image shows the original image, and the same image set as background for a position box. For the first box the background size is set to cover and the second uses contain.

Dynamically replace the background image

  1. With the box selected enter a name for this element in the ID field of the Attributes panel. In our example we will use productImage.
  2. Click the ID label to create a script for the box.
  3. Enter the script code below. This scripts constructs the URL of the image to a location in the Images folder (Resources panel) using the value from the image data field.
let imagePath = "url( images/" + record.fields.image + ".pdf )"
results.css("background-image", imagePath )

To set the path to a file on disk use the following notation:

let imagePath = "url( file:///C:/products/" + record.fields.image + ".pdf )"

Going the extra mile

Use padding and the background-origin property to add some extra white space around the image. Setting the background-origin to content-box the image will start inside the specified padding. Adding the following rule to the context_all_styles.css is all it needs (or use the Advanced option in the Box properties dialog).

#productImage {
    background-origin: content-box;
    padding: 8mm;

In the image below this extra space is marked in blue: