ImageTransform

View as Markdown

ImageTransform

ImageTransform collects Image Delivery API parameters and adds them to an image URL as a query string. Use it for the following tasks:

  • crop, trim, or pad an image without storing a second copy
  • convert an image to another format or set its compression level
  • adjust color and detail, or place one image over another

ImageTransform runs on the device and sends no request. The Image Delivery API applies the parameters when your app or a browser loads the URL.

ImageTransform() takes no arguments.

Class-Level Notes

Create a builder and apply it to a URL.

  • Create a builder with ImageTransform() and chain the methods you need. Each method records one operation and returns the same builder.
  • Call url(with:) on the image URL string and pass the builder. url(with:) is a public extension on String in the SDK (Utils.swift). It checks every recorded operation and returns a URL that includes the parameters.
  • An image asset's url property contains the URL to use. The Class-Level Snippet below fetches an asset and applies a builder to its url.
  • url(with:) writes the parameters in the order you called the methods.
  • Known issue: url(with:) replaces any query string that the URL already has when the builder contains at least one operation. A parameter such as environment=production disappears from the result. Call url(with:) on the URL without a query string, then add your own parameters to the returned URL with URLComponents.
  • ImageTransform is a class, so a builder you store and change later keeps the operations it already contains. No method removes an operation. Create a new builder for a different result.

Each operation at most once.

  • url(with:) throws ImageTransformError if a builder contains the same operation twice, for example two blur(_:) calls. The SDK compares only the kind of operation, not its value.
  • Two pairs of methods record the same operation:

Where errors surface.

  • The setters never throw. Each one records its value without checking it.
  • url(with:) runs every check and throws ImageTransformError for the first operation that fails. Each method page lists the values its operation rejects.
  • When the URL loads, the Image Delivery API answers values it cannot apply. The SDK never sees that response, because it makes no request.

Types that app code cannot create.

  • Known issue: Size and Resize declare no public initializer, so code outside the SDK cannot create either type. Calls that need one do not compile: resize(_:), dpr(_:resize:), fit(_:), Crop.aspectRatio, Canvas.aspectRatio, and OverlayType.size. Call url(with:) first, then add the width, height, dpr, fit, or overlay-width parameters to the returned URL with URLComponents. The method pages for these calls show the workaround.

Platform differences.

  • trim(_:), pad(_:), and overlay(relativeUrl:padding:) take an NSEdgeInsets. On iOS, tvOS, and watchOS, the SDK defines NSEdgeInsets as a type alias for UIEdgeInsets. On macOS, it is the Foundation type. Both take the same init(top:left:bottom:right:) labels, so the same code builds on every platform.

Rate limiting and retry.

  • ImageTransform sends no request, so no retry logic applies to it. The code that loads the URL receives any error from the Image Delivery API.

Capability Matrix

CapabilitySupportedNotes / Alternative
Create Size or Resize in app codeNoAdd width, height, and related parameters to the URL yourself
Keep a query string that the URL already hasNoCall url(with:) first, then add your own parameters to the result
Width, height, or crop size as a percentageNoSizes are UInt pixels. Add a percentage value to the URL yourself
avif output, auto=avif, or fit=coverNoAdd the parameter to the URL yourself
The same operation twice in one builderNoRecord each operation once

Method Index

Every method except url(with:) is available on any ImageTransform instance. The groups below follow what each method changes in the image.

Create and apply a builder. Available as ImageTransform(), and as url(with:) on any String.

Method NameReturnsDescription
init()A new builder with no operations.Creates an empty builder.
url(with:)The image URL, including the image parameters.Applies a builder to an image URL string.

Set the output size. Available on ImageTransform().

Method NameReturnsDescription
resize(_:)The same builder, for chaining.Sets the width, height, and resize filter.
fit(_:)The same builder, for chaining.Fits the image within a width and height.
dpr(_:resize:)The same builder, for chaining.Scales the size for a device pixel ratio.

Crop, trim, and pad. Available on ImageTransform().

Method NameReturnsDescription
crop(_:)The same builder, for chaining.Removes pixels to a size, region, or offset.
canvas(_:)The same builder, for chaining.Enlarges the canvas around the image.
trim(_:)The same builder, for chaining.Trims pixels from the edges.
pad(_:)The same builder, for chaining.Adds pixels around the edges.

Orient and layer. Available on ImageTransform().

Method NameReturnsDescription
orient(_:)The same builder, for chaining.Rotates or flips the image.
overlay(relativeUrl:overlayTypes:)The same builder, for chaining.Places another image over this one.
overlay(relativeUrl:padding:)The same builder, for chaining.Places a padded image over this one.

Choose the format and compression. Available on ImageTransform().

Method NameReturnsDescription
auto()The same builder, for chaining.Turns on automatic WebP delivery.
format(_:)The same builder, for chaining.Converts the image to another format.
qualiy(_:)The same builder, for chaining.Sets the compression level of lossy formats.
fetchFirstFrame()The same builder, for chaining.Returns the first frame of an animated GIF.

Adjust color and detail. Available on ImageTransform().

Method NameReturnsDescription
backgroundColor(_:)The same builder, for chaining.Sets the background color.
brightness(_:)The same builder, for chaining.Adjusts the brightness.
contrast(_:)The same builder, for chaining.Adjusts the contrast.
saturation(_:)The same builder, for chaining.Adjusts the intensity of the colors.
blur(_:)The same builder, for chaining.Blurs the image.
sharpen(amount:radius:threshold:)The same builder, for chaining.Sharpens the edges of objects in the image.

ImageTransformError

url(with:) and toURL() throw ImageTransformError when a check fails. It is a struct that conforms to Error and CustomDebugStringConvertible (ImageTransformError.swift:10). The SDK creates it. App code reads it.

PropertyTypeAccessDefaultDescription
messageStringRead-onlyNot applicableText that names the failed check.
debugDescriptionStringRead-onlyThe value of messageThe same text, used by print(error).

Catch the type, not the text. The SDK can reword message in any release.

String Extension

The SDK adds two public methods to String (Utils.swift:32-86):

  • url(with:) applies a builder to the URL string.
  • toURL() turns the string into a URL and adds the https scheme when the string has none. It throws ImageTransformError when Foundation cannot read the string as a URL. url(with:) calls it for you.

Format

Format is the argument of format(_:) (ImageOperations.swift:111-138). It has no raw value. The Raw value column shows the value the SDK writes.

CaseRaw valueMeaning
pjpgpjpgProgressive JPEG.
jpegjpgJPEG.
gifgifGIF.
pngpngPNG.
webpwebpWebP.
webplywebplyWebP, lossy.
webpllwebpllWebP, lossless.

Crop

Crop is the argument of crop(_:) (ImageOperations.swift:141-196). Sizes are whole pixels. The Raw value column shows the value the SDK writes.

CaseRaw valueMeaning
default(width: UInt, height: UInt)crop=<width>,<height>Crops to the size, from the center.
aspectRatio(Size, ratio: String, mode: Mode = .none)width, height, then crop=<ratio>Crops to a ratio such as "1:2". Code outside the SDK cannot create the Size.
region(width: UInt, height: UInt, xRegion: Double, yRegion: Double, mode: Mode = .none)crop=<width>,<height>,x<xRegion>,y<yRegion>Crops from a top-left corner at xRegion, yRegion.
offset(width: UInt, height: UInt, xOffset: Double, yOffset: Double, mode: Mode = .none)crop=<width>,<height>,offset-x<xOffset>,offset-y<yOffset>Crops around a center point at xOffset, yOffset.

Mode

Mode is the last value of the Crop cases that take one (ImageOperations.swift:93-108). It has no raw value.

CaseRaw valueMeaning
noneNothingDefault. Adds no flag.
safe,safeReturns the overlap of the image and the crop area instead of an error when the area runs past the edge.
smart,smartCrops with content-aware detection of the main subject.

Canvas

Canvas is the argument of canvas(_:) (ImageOperations.swift:199-244). It has the shapes of Crop without a Mode. The Raw value column shows the value the SDK writes.

CaseRaw valueMeaning
default(width: UInt, height: UInt)canvas=<width>,<height>Sets the canvas size. The API centers the canvas on the image.
aspectRatio(Size, ratio: String)width, height, then canvas=<ratio>Sets the canvas to a ratio such as "2:3". Code outside the SDK cannot create the Size.
region(width: UInt, height: UInt, xRegion: Double, yRegion: Double)canvas=<width>,<height>,x<xRegion>,y<yRegion>Places the top-left corner of the canvas at xRegion, yRegion.
offset(width: UInt, height: UInt, xOffset: Double, yOffset: Double)canvas=<width>,<height>,offset-x<xOffset>,offset-y<yOffset>Places the center of the canvas at xOffset, yOffset.

Fit

Fit is the argument of fit(_:) (ImageOperations.swift:249-270). Both cases take a Size, which code outside the SDK cannot create.

CaseRaw valueMeaning
bounds(Size)width, height, then fit=boundsConstrains the image to the width and height.
crop(Size)width, height, then fit=cropCrops the image to the width and height.

Size

Size stores a width and a height in whole pixels (ImageOperations.swift:73-89). Resize, Fit, Crop.aspectRatio, Canvas.aspectRatio, and OverlayType.size take it. Code outside the SDK cannot create a Size. The Types that app code cannot create note under Class-Level Notes gives the cause and the workaround.

PropertyTypeAccessDefaultDescription
widthUInt?Read and writenilWidth in pixels. nil writes no width.
heightUInt?Read and writenilHeight in pixels. nil writes no height.

Resize

Resize is the argument of resize(_:) and dpr(_:resize:) (ImageOperations.swift:50-69). Code outside the SDK cannot create a Resize. The Types that app code cannot create note under Class-Level Notes gives the cause and the workaround.

PropertyTypeAccessDefaultDescription
sizeSizeRead-onlyNot applicableWrites width and height.
disableUpscaleBoolRead and writefalsetrue writes disable=upscale.
filterResizeFilterRead and write.noneWrites resize-filter, unless .none.

ResizeFilter

ResizeFilter is the filter property of Resize (ImageOperations.swift:13-44). Its raw type is String.

CaseRaw valueMeaning
nonenoneDefault. Writes no resize-filter, so the API uses lanczos3.
nearestnearestUses the values of neighboring pixels.
bilinarebilinareMeant as the bilinear filter. The API lists the value bilinear, not bilinare.
bicubicbicubicUses a 4x4 area of pixels.
lanczos2lanczos2Uses the sinc resampling function.
lanczos3lanczos3Uses a closer approximation of the sinc function.

Orientation

Orientation is the argument of orient(_:) (ImageOperations.swift:273-293). Its raw type is Int, and the SDK writes orient=<raw value>.

CaseRaw valueMeaning
default1Keeps the default orientation.
flipHorizontal2Flips horizontally.
flipHorizontalVertical3Flips horizontally and vertically.
flipVerticle4Flips vertically.
flipHorizontalLeft5Flips horizontally, then rotates 90 degrees left.
right6Rotates 90 degrees right.
flipHorizontalRight7Flips horizontally, then rotates 90 degrees right.
left8Rotates 90 degrees left.

OverlayType

OverlayType is an element of the overlayTypes array of overlay(relativeUrl:overlayTypes:) (ImageOperations.swift:298-322). It has no raw value.

CaseRaw valueMeaning
align(OverlayAlign)overlay-align=<value>Positions the overlay image.
repeat(OverlayRepeat)overlay-repeat=<value>Repeats the overlay image.
size(Size)overlay-width, overlay-heightSizes the overlay image. Code outside the SDK cannot create the Size.

OverlayAlign

OverlayAlign is the value of OverlayType.align (ImageOperations.swift:325-350). Its raw type is String. Without an alignment, the API places the overlay at middle,center.

CaseRaw valueMeaning
toptopTop of the image.
bottombottomBottom of the image.
leftleftLeft of the image.
rightrightRight of the image.
middelmiddelMeant as the vertical middle. The API lists the value middle, not middel.
centercenterHorizontal center of the image.
topLefttop,leftTop-left corner.
topRighttop,rightTop-right corner.
bottomLeftbottom,leftBottom-left corner.
bottomRightbottom,rightBottom-right corner.

OverlayRepeat

OverlayRepeat is the value of OverlayType.repeat (ImageOperations.swift:353-360). Its raw type is String.

CaseRaw valueMeaning
bothbothRepeats horizontally and vertically.
horizontalxRepeats horizontally.
verticleyRepeats vertically.

Color

Color is the argument of backgroundColor(_:) (ImageOperations.swift:364-396). It has no raw value. The Raw value column shows the value the SDK writes.

CaseRaw valueMeaning
hex(String)bg-color=<hex>A 3-digit or 6-digit hexadecimal color without #, for example "FF0000".
rgb(red: UInt, green: UInt, blue: UInt)bg-color=<red><green><blue>Red, green, and blue from 0 to 255. The SDK joins the values without commas.
rgba(red: UInt, green: UInt, blue: UInt, alpha: Double)bg-color=<red><green><blue><alpha>Red, green, and blue from 0 to 255, and alpha from 0.0 to 1.0. The SDK joins the values without commas.

When your file also imports SwiftUI, Color names two types. Pass .hex(...) to backgroundColor(_:) and Swift selects the SDK type, or write ContentstackSwift.Color.

NSEdgeInsets

NSEdgeInsets is the argument of trim(_:), pad(_:), and overlay(relativeUrl:padding:). On iOS, tvOS, and watchOS, the SDK declares public typealias NSEdgeInsets = UIEdgeInsets (ImageOperation.swift:9-12). On macOS, NSEdgeInsets is the Foundation type.

PropertyTypeAccessDefaultDescription
topCGFloatRead and writeNot applicableTop edge, first in the written value.
leftCGFloatRead and writeNot applicableLeft edge, last in the written value.
bottomCGFloatRead and writeNot applicableBottom edge, third in the written value.
rightCGFloatRead and writeNot applicableRight edge, second in the written value.

The SDK writes the four values in the order top, right, bottom, left, as the API expects. It writes each as a decimal, for example 25.0.

Class-Level Snippet

The snippet below fetches an image asset, requests a WebP version at quality 80 cropped to 300 by 400 pixels, and prints the resulting URL.

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
    .fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
        switch result {
        case .success(let asset):
            let transform = ImageTransform()
                .crop(.default(width: 300, height: 400))
                .format(.webp)
                .qualiy(80)
            do {
                let url = try asset.url.url(with: transform)
                print(url.absoluteString)
                // The asset URL followed by ?crop=300,400&format=webp&quality=80
            } catch {
                print(error)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

Each method of the ImageTransform class has its own section below, with its parameters, validation rules, behavior, and examples.

auto()

auto() asks the Image Delivery API to deliver the image in WebP format to clients that support it.

This method takes no parameters.

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation, because auto() takes no value.
  • Errors that do occur come from the url(with:) call that follows, not from auto().

Additional Resource Refer to Enable auto optimization in the Image Delivery API reference for the values the API accepts.

Behavior

  • auto() writes auto=webp.
  • The API also accepts auto=avif. auto() has no argument for it. Add auto=avif to the URL yourself with URLComponents after you call url(with:).
  • When the builder also holds a format(_:) operation, the API serves WebP to clients that support it and the format value to all other clients.
  • The API does not apply auto to GIF files.
  • The API reference asks for an accept header of image/webp on the image request, so that the server returns the converted image.

Example

Basic usage: deliver WebP where the client supports it

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().auto()

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?auto=webp
} catch {
    print(error)
}

Fall back to progressive JPEG for clients without WebP support

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .auto()
    .format(.pjpg)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?auto=webp&format=pjpg
} catch {
    print(error)
}

backgroundColor(_:)

backgroundColor(_:) sets the background color of the image, which fills padding, a canvas, or transparent pixels.

NameTypeDescription
color (required)Color

Background color as hex, RGB, or RGBA.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • backgroundColor(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError in the following three cases, because the API accepts only these forms:
    • A .hex value that is not exactly 3 or 6 hexadecimal digits. A leading # also fails the check.
    • An .rgb component greater than 255.
    • An .rgba component greater than 255, or an alpha outside 0.0 to 1.0.
  • Known issue: .rgb and .rgba join the values without commas, so .rgb(red: 140, green: 220, blue: 123) writes bg-color=140220123 instead of the 140,220,123 that the API expects. Use .hex instead, as the second example below shows.
  • Errors that do occur come from the url(with:) call that follows, not from backgroundColor(_:).

Additional Resource Refer to Change background color using hexadecimal value in the Image Delivery API reference for the values the API accepts.

Behavior

  • backgroundColor(_:) writes bg-color=<value>, for example bg-color=FF0000.
  • The API uses the color for the padding that pad(_:) adds, for the canvas that canvas(_:) adds, and for transparent pixels.
  • When your file also imports SwiftUI, Color names two types. Pass .hex(...) directly to backgroundColor(_:) and Swift selects the SDK type, or write ContentstackSwift.Color.

Example

Basic usage: set a red background with a hex value

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png"
let transform = ImageTransform().backgroundColor(.hex("FF0000"))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png?bg-color=FF0000
} catch {
    print(error)
}

Workaround: convert RGB values to a hex code

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png"
// .rgb writes the values without commas, so pass the same color as hex.
let hex = String(format: "%02X%02X%02X", 140, 220, 123)
let transform = ImageTransform().backgroundColor(.hex(hex))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png?bg-color=8CDC7B
} catch {
    print(error)
}

Error handling: a hex value with a leading number sign

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png"
let transform = ImageTransform().backgroundColor(.hex("#FF0000"))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
} catch let error as ImageTransformError {
    // Thrown because the hex value holds a character other than a hexadecimal digit
    print("Image parameters rejected:", error.message)
} catch {
    print(error)
}

blur(_:)

blur(_:) decreases the focus and clarity of the image.

NameTypeDescription
blur (required)UInt

Blur strength, from 1 to 999.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • blur(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError if blur is 0 or 1000 or more, because the API accepts a blur strength from 1 to 1000. The SDK check also rejects 1000 itself.
  • Errors that do occur come from the url(with:) call that follows, not from blur(_:).

Additional Resource Refer to Increase blurriness in the Image Delivery API reference for the values the API accepts.

Behavior

  • blur(_:) writes blur=<blur>, for example blur=40.
  • A higher value returns a blurrier image.
  • The API also accepts a decimal value. blur is a UInt, so it cannot express one.

Example

Basic usage: blur an image by 40

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().blur(40)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?blur=40
} catch {
    print(error)
}

Error handling: a value outside the accepted range

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().blur(0)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
} catch let error as ImageTransformError {
    // Thrown because 0 is below the accepted range
    print("Image parameters rejected:", error.message)
} catch {
    print(error)
}

brightness(_:)

brightness(_:) increases or decreases the perceived light that the image reflects.

NameTypeDescription
value (required)Double

Brightness change, from -100 to 100.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • brightness(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError if value is less than -100 or greater than 100, because the API accepts a brightness change from -100 to 100.
  • Errors that do occur come from the url(with:) call that follows, not from brightness(_:).

Additional Resource Refer to Increase brightness in the Image Delivery API reference for the values the API accepts.

Behavior

  • brightness(_:) writes brightness=<value> as a decimal, for example brightness=30.0 for 30.
  • A positive value brightens the image, and a negative value darkens it.
  • 0 leaves the image unchanged. 100 returns an entirely white image, and -100 returns an entirely black image.

Example

Basic usage: brighten an image by 30

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().brightness(30)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?brightness=30.0
} catch {
    print(error)
}

Darken an image by 50

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().brightness(-50)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?brightness=-50.0
} catch {
    print(error)
}

canvas(_:)

canvas(_:) enlarges the canvas that surrounds the image.

NameTypeDescription
canvas (required)Canvas

Canvas shape, size, and position.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • canvas(_:) records the value and does not check it. url(with:) writes the size and position without a range check.
  • url(with:) throws ImageTransformError if a .aspectRatio value carries a Size with no width and no height, because the API needs one of them to size the canvas. App code cannot create a Size, so .aspectRatio is not available outside the SDK.
  • Errors that do occur come from the url(with:) call that follows, not from canvas(_:).
  • The API expects a canvas at least as large as the image.

Additional Resource Refer to Canvas by width and height in the Image Delivery API reference for the values the API accepts.

Behavior

  • canvas(_:) writes canvas=<value>. Each Canvas case writes a different value shape:
    • .default(width:height:) writes canvas=<width>,<height> and centers the image on the canvas.
    • .region(width:height:xRegion:yRegion:) writes canvas=<width>,<height>,x<xRegion>,y<yRegion>, where xRegion and yRegion set the top-left corner of the canvas.
    • .offset(width:height:xOffset:yOffset:) writes canvas=<width>,<height>,offset-x<xOffset>,offset-y<yOffset>, where xOffset and yOffset set the center point of the canvas. The API reads offsets as percentages.
  • The API fills the canvas with white, or with transparent pixels for formats that support transparency. Use the backgroundColor(_:) method to set another color.
  • When a builder holds both canvas(_:) and pad(_:), the API applies the canvas and does not apply the padding.
  • width and height are whole pixels, so canvas(_:) cannot express a percentage size such as 0.7.

Example

Basic usage: set a 700 by 800 pixel canvas

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().canvas(.default(width: 700, height: 800))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?canvas=700,800
} catch {
    print(error)
}

Place the canvas around an offset center point

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .canvas(.offset(width: 700, height: 800, xOffset: 0.65, yOffset: 0.8))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?canvas=700,800,offset-x0.65,offset-y0.8
} catch {
    print(error)
}

contrast(_:)

contrast(_:) increases or decreases the difference between the darkest and lightest tones in the image.

NameTypeDescription
value (required)Double

Contrast change, from -100 to 100.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • contrast(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError if value is less than -100 or greater than 100, because the API accepts a contrast change from -100 to 100.
  • Errors that do occur come from the url(with:) call that follows, not from contrast(_:).

Additional Resource Refer to Increase contrast in the Image Delivery API reference for the values the API accepts.

Behavior

  • contrast(_:) writes contrast=<value> as a decimal, for example contrast=20.0 for 20.
  • A positive value increases the contrast, and a negative value reduces it.
  • 0 leaves the image unchanged, and -100 returns a neutral gray image.

Example

Basic usage: increase the contrast by 20

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().contrast(20)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?contrast=20.0
} catch {
    print(error)
}

Reduce the contrast with a decimal value

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().contrast(-35.5)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?contrast=-35.5
} catch {
    print(error)
}

crop(_:)

crop(_:) removes pixels from the image to a set size, from a set corner, or around a set center point.

NameTypeDescription
crop (required)Crop

Crop shape, size, position, and mode.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • crop(_:) records the value and does not check it. url(with:) writes the size and position without a range check.
  • url(with:) throws ImageTransformError if a .aspectRatio value carries a Size with no width and no height, because the API needs one of them to size the crop. App code cannot create a Size, so .aspectRatio is not available outside the SDK.
  • Errors that do occur come from the url(with:) call that follows, not from crop(_:).
  • When the URL loads, the API rejects a crop area that runs past the edge of the image unless you pass .safe as the mode.

Additional Resource Refer to Crop by width and height in the Image Delivery API reference for the values the API accepts.

Behavior

  • crop(_:) writes crop=<value>. Each Crop case writes a different value shape:
    • .default(width:height:) writes crop=<width>,<height> and crops from the center.
    • .region(width:height:xRegion:yRegion:mode:) writes crop=<width>,<height>,x<xRegion>,y<yRegion>, where xRegion and yRegion set the top-left corner of the crop.
    • .offset(width:height:xOffset:yOffset:mode:) writes crop=<width>,<height>,offset-x<xOffset>,offset-y<yOffset>, where xOffset and yOffset set the center point of the crop. The API reads offsets as percentages.
  • A mode of .safe or .smart adds ,safe or ,smart at the end. .none, the default, adds nothing.
    • With .safe, the API returns the overlap of the image and the crop area, which can be smaller than the size you set.
    • With .smart, the API uses content-aware cropping to keep the most important part of the image, such as a face.
  • width and height are whole pixels, so crop(_:) cannot express a percentage size such as 0.5.
  • xRegion, yRegion, xOffset, and yOffset are Double values, and the SDK writes them as decimals, for example x150.0.

Example

Basic usage: crop an image to 300 by 400 pixels

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().crop(.default(width: 300, height: 400))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?crop=300,400
} catch {
    print(error)
}

Crop a region from a top-left corner in safe mode

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .crop(.region(width: 300, height: 400, xRegion: 150, yRegion: 75, mode: .safe))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?crop=300,400,x150.0,y75.0,safe
} catch {
    print(error)
}

Crop around an offset center point with smart cropping

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .crop(.offset(width: 300, height: 400, xOffset: 10.5, yOffset: 10.5, mode: .smart))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?crop=300,400,offset-x10.5,offset-y10.5,smart
} catch {
    print(error)
}

dpr(_:resize:)

dpr(_:resize:) scales the image for a device pixel ratio, together with the width or height that the ratio applies to.

NameTypeDescription
dpr (required)UInt

Device pixel ratio, for example 2.

Default: Not applicable
resize (required)Resize

Width or height that the ratio multiplies.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • Known issue: Resize and Size declare no public initializer, so app code cannot create the Resize value that dpr(_:resize:) needs, and a call to dpr(_:resize:) does not compile. Call url(with:) for your other parameters, then add width or height and dpr to the returned URL with URLComponents, as the example below shows.
  • dpr(_:resize:) records both values and does not check them.
  • url(with:) throws ImageTransformError if dpr is 10000 or more, because the API accepts a whole-number ratio up to 10000. The SDK check also rejects 10000 itself.
  • url(with:) accepts 0, although the API range for a whole number starts at 1.
  • url(with:) does not check that resize holds a width or a height, although the API needs one of them.
  • url(with:) throws ImageTransformError if the builder also holds resize(_:), because both methods record the resize operation.
  • Errors that do occur come from the url(with:) call that follows, not from dpr(_:resize:).

Additional Resource Refer to Set device pixel ratio in the Image Delivery API reference for the values the API accepts.

Behavior

  • dpr(_:resize:) records two operations. It writes the resize parameters first, as resize(_:) does, then dpr=<dpr>.
  • With only a width or only a height, the API keeps the aspect ratio of the image.
  • The API also accepts a decimal ratio, such as 1.5. dpr is a UInt, so it cannot express one.

Example

Workaround: add the width and pixel ratio to the URL yourself

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().format(.webp)

do {
    let url = try imageURL.url(with: transform)
    // Resize has no public initializer, so add width and dpr yourself.
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(contentsOf: [
        URLQueryItem(name: "width", value: "300"),
        URLQueryItem(name: "dpr", value: "2")
    ])
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=webp&width=300&dpr=2
} catch {
    print(error)
}

fetchFirstFrame()

fetchFirstFrame() returns the first frame of an animated GIF as a still image.

This method takes no parameters.

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation, because fetchFirstFrame() takes no value.
  • Errors that do occur come from the url(with:) call that follows, not from fetchFirstFrame().

Additional Resource Refer to Fetch first frame in the Image Delivery API reference for the values the API accepts.

Behavior

  • fetchFirstFrame() writes frame=1.
  • The API applies frame only to animated GIF files.
  • The API can return only the first frame. No method selects a different frame.

Example

Basic usage: read the first frame of an animated GIF

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/banner.gif"
let transform = ImageTransform().fetchFirstFrame()

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/banner.gif?frame=1
} catch {
    print(error)
}

fit(_:)

fit(_:) fits the image within a width and height, either by constraining it or by cropping it.

NameTypeDescription
fit (required)Fit

Fit mode with the width and height to fit.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • Known issue: Both Fit cases take a Size, which declares no public initializer. As a result, app code cannot create a Fit value, and a call to fit(_:) does not compile. Call url(with:) for your other parameters, then add width, height, and fit to the returned URL with URLComponents, as the example below shows.
  • fit(_:) records the value and does not check it. url(with:) does not check that the Size holds both a width and a height, although the API needs both.
  • Errors that do occur come from the url(with:) call that follows, not from fit(_:).

Additional Resource Refer to Fit to bounds in the Image Delivery API reference for the values the API accepts.

Behavior

  • fit(_:) writes width and height from the Size, then fit=bounds for .bounds or fit=crop for .crop.
    • bounds constrains the image to the width and height.
    • crop crops the image to the width and height.
  • The API also accepts fit=cover, which fills the whole area and crops the rest from the center. Fit has no case for it.
  • fit(_:) writes its own width and height. A builder that also sets a size through another method sends each parameter twice.

Example

Workaround: add the fit parameters to the URL yourself

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().format(.pjpg)

do {
    let url = try imageURL.url(with: transform)
    // Size has no public initializer, so add width, height, and fit yourself.
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(contentsOf: [
        URLQueryItem(name: "width", value: "300"),
        URLQueryItem(name: "height", value: "300"),
        URLQueryItem(name: "fit", value: "bounds")
    ])
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=pjpg&width=300&height=300&fit=bounds
} catch {
    print(error)
}

format(_:)

format(_:) converts the image to another format.

NameTypeDescription
format (required)Format

Output format, for example .webp.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. The Format type allows only its seven cases.
  • Errors that do occur come from the url(with:) call that follows, not from format(_:).

Additional Resource Refer to Convert Formats in the Image Delivery API reference for the values the API accepts.

Behavior

  • format(_:) writes format=<value>. .jpeg writes jpg, and each other case writes its own name. The ImageTransform class page lists every case.
  • The API also accepts avif and auto. Format has no case for them. Add the value to the URL yourself with URLComponents after you call url(with:).
  • The API applies quality only to jpg, pjpg, webply, and avif.
  • The API does not convert to GIF.
  • A HEIC source image needs an output format, because few browsers display HEIC.
  • When the builder also holds auto(), the API serves WebP to clients that support it and does not apply format for them.

Example

Basic usage: convert an image to PNG

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().format(.png)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=png
} catch {
    print(error)
}

Convert to JPEG, which writes the value jpg

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.png"
let transform = ImageTransform().format(.jpeg)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.png?format=jpg
} catch {
    print(error)
}

init()

init() creates an ImageTransform builder that holds no operations.

This method takes no parameters.

Returns: ImageTransform. A new builder with no operations.

Validation

  • There is no client-side validation. init() cannot fail.

Additional Resource Refer to the Image Delivery API reference for every parameter that a builder can add.

Behavior

  • You call it as ImageTransform(). Chain the methods you need on the result.
  • Each call creates a separate builder. Operations that you record on one builder never appear on another.
  • A builder with no operations leaves the URL as it is. url(with:) returns the same URL and keeps its query string. It adds only the https scheme when the string has none.

Example

Basic usage: create a builder and apply it to an image URL

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .format(.png)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=png
} catch {
    print(error)
}

Edge case: an empty builder returns the URL unchanged

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?environment=ENVIRONMENT"

do {
    let url = try imageURL.url(with: ImageTransform())
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?environment=ENVIRONMENT
} catch {
    print(error)
}

orient(_:)

orient(_:) rotates or flips the image.

NameTypeDescription
orient (required)Orientation

Rotation or flip to apply, for example .right.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. The Orientation type allows only its eight cases.
  • Errors that do occur come from the url(with:) call that follows, not from orient(_:).

Additional Resource Refer to Orient the image right in the Image Delivery API reference for the values the API accepts.

Behavior

  • orient(_:) writes orient=<raw value>, a number from 1 to 8. The ImageTransform class page lists what each case does.
  • The SDK spells one case flipVerticle. It writes 4, which flips the image vertically.
  • The API also corrects the orientation of an image whose EXIF data holds orientation details.

Example

Basic usage: rotate an image 90 degrees right

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().orient(.right)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?orient=6
} catch {
    print(error)
}

Flip horizontally, then rotate right

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().orient(.flipHorizontalRight)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?orient=7
} catch {
    print(error)
}

overlay(relativeUrl:overlayTypes:)

overlay(relativeUrl:overlayTypes:) places another image on top of this one, with optional alignment and repetition.

NameTypeDescription
relativeUrl (required)String

Relative URL of the overlay image.

Default: Not applicable
overlayTypes[OverlayType]

Alignment, repetition, or size of the overlay.

Default: Empty array

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. url(with:) writes an empty relativeUrl as overlay=, and writes two .align entries as two overlay-align parameters.
  • Known issue: OverlayAlign.middel writes overlay-align=middel, a value the API does not list. The API expects middle. Leave out .align to get the API default of middle,center, or add overlay-align=middle to the URL yourself with URLComponents after you call url(with:).
  • OverlayType.size takes a Size, which app code cannot create. Add overlay-width or overlay-height to the URL yourself with URLComponents after you call url(with:), as the last example below shows.
  • url(with:) throws ImageTransformError if the builder also holds overlay(relativeUrl:padding:), because both methods record the overlay operation.
  • Errors that do occur come from the url(with:) call that follows, not from overlay(relativeUrl:overlayTypes:).

Additional Resource Refer to Overlay image in the Image Delivery API reference for the values the API accepts.

Behavior

  • overlay(relativeUrl:overlayTypes:) writes overlay=<relativeUrl>, then one parameter for each entry in overlayTypes, in array order:
    • .align(OverlayAlign) writes overlay-align, for example overlay-align=bottom,right.
    • .repeat(OverlayRepeat) writes overlay-repeat with x, y, or both.
    • .size(Size) writes overlay-width and overlay-height.
  • relativeUrl is the path of the overlay image, such as /v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png. The SDK writes it as given.
  • Without an alignment, the API places the overlay at middle,center.
  • When the overlay image is larger than the image, the API crops the overlay.
  • The ImageTransform class page lists every OverlayAlign and OverlayRepeat case.

Example

Basic usage: place a logo over an image

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .overlay(relativeUrl: "/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png")

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?overlay=/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png
} catch {
    print(error)
}

All parameters: align the overlay and repeat it horizontally

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .overlay(relativeUrl: "/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png",
             overlayTypes: [.align(.bottomRight), .repeat(.horizontal)])

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?overlay=/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png&overlay-align=bottom,right&overlay-repeat=x
} catch {
    print(error)
}

Workaround: set the overlay width yourself

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .overlay(relativeUrl: "/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png",
             overlayTypes: [.align(.bottomRight)])

do {
    // OverlayType.size needs a Size, which app code cannot create, so add overlay-width yourself.
    let url = try imageURL.url(with: transform)
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(URLQueryItem(name: "overlay-width", value: "100"))
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?overlay=/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png&overlay-align=bottom,right&overlay-width=100
} catch {
    print(error)
}

overlay(relativeUrl:padding:)

overlay(relativeUrl:padding:) places another image on top of this one and adds padding around the overlay image.

NameTypeDescription
relativeUrl (required)String

Relative URL of the overlay image.

Default: Not applicable
padding (required)NSEdgeInsets

Pixels to add to each edge of the overlay.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. url(with:) writes an empty relativeUrl and negative padding as given.
  • url(with:) throws ImageTransformError if the builder also holds overlay(relativeUrl:overlayTypes:), because both methods record the overlay operation.
  • Errors that do occur come from the url(with:) call that follows, not from overlay(relativeUrl:padding:).

Additional Resource Refer to Overlay pad in the Image Delivery API reference for the values the API accepts.

Behavior

  • overlay(relativeUrl:padding:) records two operations and writes overlay=<relativeUrl>&overlay-pad=<top>,<right>,<bottom>,<left>.
  • The SDK writes each padding value as a decimal, for example overlay-pad=10.0,10.0,10.0,10.0, and always writes all four.
  • The API fills the padding with white, or with transparent pixels when the overlay format supports transparency.
  • Does not take overlay alignment, repetition, or size. Add overlay-align, overlay-repeat, or overlay-width to the URL yourself with URLComponents after you call url(with:).

Example

Basic usage: place a padded logo over an image

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let padding = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let transform = ImageTransform()
    .overlay(relativeUrl: "/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png", padding: padding)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?overlay=/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png&overlay-pad=10.0,10.0,10.0,10.0
} catch {
    print(error)
}

Add an alignment to a padded overlay

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let padding = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let transform = ImageTransform()
    .overlay(relativeUrl: "/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png", padding: padding)

do {
    // Both overlay methods record the same operation, so add the alignment yourself.
    let url = try imageURL.url(with: transform)
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(URLQueryItem(name: "overlay-align", value: "top,left"))
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?overlay=/v3/assets/API_KEY/ASSET_UID/FILE_UID/logo.png&overlay-pad=10.0,10.0,10.0,10.0&overlay-align=top,left
} catch {
    print(error)
}

pad(_:)

pad(_:) adds pixels to the top, right, bottom, and left edges of the image, for example to add whitespace or a border.

NameTypeDescription
padding (required)NSEdgeInsets

Pixels to add to each edge.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. url(with:) writes negative values as given.
  • Errors that do occur come from the url(with:) call that follows, not from pad(_:).

Additional Resource Refer to Add padding in the Image Delivery API reference for the values the API accepts.

Behavior

  • pad(_:) writes pad=<top>,<right>,<bottom>,<left>, the order that the API expects. The SDK writes each value as a decimal, for example pad=10.0,10.0,10.0,10.0.
  • The SDK always writes all four values. Pass the same number in each NSEdgeInsets field to pad every edge by the same amount.
  • The API fills the padding with white, or with transparent pixels when the image and the output format support transparency.
  • Add the backgroundColor(_:) method to fill the padding with a color, for example a red border.
  • When a builder holds both pad(_:) and canvas(_:), the API applies the canvas and does not apply the padding.

Example

Basic usage: add a 10-pixel red border

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let border = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let transform = ImageTransform()
    .pad(border)
    .backgroundColor(.hex("FF0000"))

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?pad=10.0,10.0,10.0,10.0&bg-color=FF0000
} catch {
    print(error)
}

qualiy(_:)

qualiy(_:) sets the compression level of an image in a lossy format.

NameTypeDescription
quality (required)UInt

Compression level as a percentage, from 1 to 100.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • qualiy(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError if quality is 0 or more than 100, because the API reads the value as a whole-number percentage from 1 to 100.
  • Errors that do occur come from the url(with:) call that follows, not from qualiy(_:).

Additional Resource Refer to Quality in the Image Delivery API reference for the values the API accepts.

Behavior

  • The SDK spells the method name qualiy. It writes the quality parameter, for example quality=60.
  • A lower value returns a smaller file at a lower quality.
  • The API applies quality to JPEG, progressive JPEG, AVIF, and lossy WebP images. It does not apply the value to formats that are not lossy, such as GIF and PNG.
  • When you set only quality and the output image is larger than the original, the API returns the original image.
  • Combine qualiy(_:) with the format(_:) method to convert the image to a lossy format first.

Example

Basic usage: compress a JPEG to quality 60

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().qualiy(60)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?quality=60
} catch {
    print(error)
}

Convert to lossy WebP and set the quality

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .format(.webply)
    .qualiy(80)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=webply&quality=80
} catch {
    print(error)
}

resize(_:)

resize(_:) sets the width and height of the image, and can turn off upscaling and pick a resize filter.

NameTypeDescription
resize (required)Resize

Size, upscaling flag, and filter to apply.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • Known issue: Resize and Size declare no public initializer, so app code cannot create the Resize value that resize(_:) needs, and a call to resize(_:) does not compile. Call url(with:) for your other parameters, then add width, height, disable, and resize-filter to the returned URL with URLComponents, as the example below shows.
  • resize(_:) records the value and does not check it. url(with:) writes the width and height without a range check. The API accepts a pixel width or height from 1 to 8192.
  • url(with:) throws ImageTransformError if the builder also holds dpr(_:resize:), because both methods record the resize operation.
  • Errors that do occur come from the url(with:) call that follows, not from resize(_:).

Additional Resource Refer to Resize Images in the Image Delivery API reference for the values the API accepts.

Behavior

  • resize(_:) writes up to four parameters from the Resize properties, in the order of the list below:
    • width=<size.width> and height=<size.height>, each only when the value is not nil.
    • disable=upscale when disableUpscale is true.
    • resize-filter=<filter> when filter is not .none. The .bilinare case writes bilinare, which is not a value the API lists. The API lists bilinear.
  • With only a width or only a height, the API keeps the aspect ratio of the image.
  • The API upscales the image when the size you set is larger than the source. disable=upscale turns that off.
  • Size holds whole pixels, so resize(_:) cannot express a percentage such as 0.5 or 250p.
  • The API does not resize GIF files.
  • Without a width or height, the API returns the original image for a resize-filter value. The API uses lanczos3 when you set no filter.

Example

Workaround: add the resize parameters to the URL yourself

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().format(.webp)

do {
    let url = try imageURL.url(with: transform)
    // Resize has no public initializer, so add width, disable, and resize-filter yourself.
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(contentsOf: [
        URLQueryItem(name: "width", value: "300"),
        URLQueryItem(name: "disable", value: "upscale"),
        URLQueryItem(name: "resize-filter", value: "bicubic")
    ])
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=webp&width=300&disable=upscale&resize-filter=bicubic
} catch {
    print(error)
}

saturation(_:)

saturation(_:) increases or decreases the intensity of the colors in the image.

NameTypeDescription
value (required)Double

Saturation change, from -100 to 100.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • saturation(_:) records the value and does not check it.
  • url(with:) throws ImageTransformError if value is less than -100 or greater than 100, because the API accepts a saturation change from -100 to 100.
  • Errors that do occur come from the url(with:) call that follows, not from saturation(_:).

Additional Resource Refer to Increase saturation in the Image Delivery API reference for the values the API accepts.

Behavior

  • saturation(_:) writes saturation=<value> as a decimal, for example saturation=50.0 for 50.
  • A positive value intensifies the colors, and a negative value mutes them.
  • 0 leaves the image unchanged, and -100 returns a grayscale image.

Example

Basic usage: increase the saturation by 50

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().saturation(50)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?saturation=50.0
} catch {
    print(error)
}

Convert an image to grayscale

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().saturation(-100)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?saturation=-100.0
} catch {
    print(error)
}

sharpen(amount:radius:threshold:)

sharpen(amount:radius:threshold:) increases the definition of the edges of objects in the image.

NameTypeDescription
amount (required)UInt

Contrast added at the edges, from 0 to 10.

Default: Not applicable
radius (required)UInt

Width of the sharpened edge band, from 1 to 1000.

Default: Not applicable
threshold (required)UInt

Minimum edge strength to sharpen, from 0 to 255.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • sharpen(amount:radius:threshold:) records the values and does not check them.
  • url(with:) throws ImageTransformError in the following three cases, because the API accepts only these ranges:
    • amount is greater than 10.
    • radius is 0 or greater than 1000.
    • threshold is greater than 255.
  • Errors that do occur come from the url(with:) call that follows, not from sharpen(amount:radius:threshold:).

Additional Resource Refer to Increase sharpness in the Image Delivery API reference for the values the API accepts.

Behavior

  • sharpen(amount:radius:threshold:) writes sharpen=a<amount>,r<radius>,t<threshold>, for example sharpen=a2,r1000,t2.
  • amount sets the contrast that the API adds to the edges.
  • radius sets the width of the band of pixels around each edge that the API sharpens. A larger image needs a larger radius for the same effect.
  • threshold leaves edges below that strength unchanged, so the API sharpens only the more noticeable edges.
  • The API also accepts decimal values for amount and radius, and a percentage radius such as 50p. The parameters are UInt, so sharpen(amount:radius:threshold:) cannot express them.

Example

All parameters: sharpen the edges of an image

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().sharpen(amount: 2, radius: 1000, threshold: 2)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?sharpen=a2,r1000,t2
} catch {
    print(error)
}

Error handling: an amount outside the accepted range

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().sharpen(amount: 15, radius: 5, threshold: 2)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
} catch let error as ImageTransformError {
    // Thrown because amount is greater than 10
    print("Image parameters rejected:", error.message)
} catch {
    print(error)
}

trim(_:)

trim(_:) removes pixels from the top, right, bottom, and left edges of the image.

NameTypeDescription
edgeInset (required)NSEdgeInsets

Pixels to remove from each edge.

Default: Not applicable

Returns: ImageTransform. The same builder, for chaining.

Validation

  • There is no client-side validation. url(with:) writes negative values or values larger than the image as given.
  • Errors that do occur come from the url(with:) call that follows, not from trim(_:).

Additional Resource Refer to Trim image in the Image Delivery API reference for the values the API accepts.

Behavior

  • trim(_:) writes trim=<top>,<right>,<bottom>,<left>, the order that the API expects. NSEdgeInsets takes its values in the order top, left, bottom, right, so the written order differs from the initializer order.
  • The SDK writes each value as a decimal, for example trim=25.0,50.0,75.0,100.0.
  • The SDK always writes all four values. The API also accepts one, two, or three values as CSS-style shorthand. Pass the same number in each NSEdgeInsets field to trim every edge by the same amount.
  • On iOS, tvOS, and watchOS, NSEdgeInsets is the SDK's type alias for UIEdgeInsets. On macOS, it is the Foundation type.

Example

Basic usage: trim a different amount from each edge

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let edges = NSEdgeInsets(top: 25, left: 100, bottom: 75, right: 50)
let transform = ImageTransform().trim(edges)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?trim=25.0,50.0,75.0,100.0
} catch {
    print(error)
}

url(with:)

url(with:) adds the parameters that an ImageTransform builder holds to an image URL string and returns the result as a URL.

The SDK declares it in a public extension on String: func url(with imageTransform: ImageTransform) throws -> URL.

NameTypeDescription
with (required)ImageTransform

The builder whose operations to add.

Default: Not applicable

Returns: URL. The image URL, including the image parameters.

Validation

url(with:) throws ImageTransformError in the five cases below. It checks the first two cases before it checks any operation value. It then checks each operation in the order you recorded it and throws for the first one that fails. The five cases are:

  • The builder holds the same operation twice, because each operation writes its own parameter once. The SDK compares only the kind of operation, so blur(10) and blur(20) count as the same operation.
  • Foundation cannot read the string as a URL.
  • A value falls outside the range that its method accepts, because the Image Delivery API accepts only that range. The method pages list each range.
  • A Crop.aspectRatio or Canvas.aspectRatio value carries a Size with no width and no height, because the API needs one of them to size an aspect-ratio crop or canvas.
  • A Color value holds a hex code that is not 3 or 6 hexadecimal digits, or a component outside its range.

Catch ImageTransformError by type. Its message property describes the failed check.

Additional Resource Refer to the Image Delivery API reference for the values the API accepts for each parameter.

Behavior

  • url(with:) makes no request. It builds the URL on the device. The Image Delivery API applies the parameters when your app or a browser loads the URL.
  • It writes the parameters in the order you called the builder's methods. Each method page names the parameter it writes.
  • Known issue: When the builder holds at least one operation, url(with:) replaces any query string that the URL already has. Call url(with:) on the URL without a query string, then add your own parameters to the result with URLComponents, as the last example below shows.
  • A builder with no operations returns the URL unchanged, query string included.
  • url(with:) reads the builder and does not change it, so you can apply one builder to several URLs.
  • url(with:) calls toURL(), the other public String method in the SDK, which adds the https scheme when the string has none.
    • A string that starts with // becomes https://....
    • A string with no scheme and no //, such as images.contentstack.io/..., becomes https:images.contentstack.io/..., which a client cannot load. Pass the full URL from the asset's url property.
  • Foundation percent-encodes characters that a URL cannot hold, such as a space in the file name.

Example

Basic usage: crop an image and convert it to WebP

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .crop(.default(width: 300, height: 400))
    .format(.webp)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?crop=300,400&format=webp
} catch {
    print(error)
}

Error handling: catch a value that the SDK rejects

import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform()
    .blur(10)
    .blur(20)

do {
    let url = try imageURL.url(with: transform)
    print(url.absoluteString)
} catch let error as ImageTransformError {
    // Thrown because the builder holds two blur operations
    print("Image parameters rejected:", error.message)
} catch {
    print(error)
}

Edge case: add your own query parameters after the image parameters

import Foundation
import ContentstackSwift

let imageURL = "https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg"
let transform = ImageTransform().format(.webp)

do {
    // url(with:) replaces an existing query string, so add other parameters afterward.
    let url = try imageURL.url(with: transform)
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    components?.queryItems?.append(URLQueryItem(name: "environment", value: "ENVIRONMENT"))
    print(components?.url?.absoluteString ?? imageURL)
    // https://images.contentstack.io/v3/assets/API_KEY/ASSET_UID/FILE_UID/owl.jpg?format=webp&environment=ENVIRONMENT
} catch {
    print(error)
}