DEV Community

Maxwell
Maxwell

Posted on

Longest Edge, Same Aspect: Batch-Resizing Photos with Lanczos in Swift

When a shop asks for photos "no longer than 2000 pixels on the long edge," or you want a set small enough to email, the job is simple to describe and easy to do badly. You have to keep the aspect ratio, refuse to invent pixels by scaling up, and not soften every edge by drawing a 48-megapixel image into a small bitmap with a cheap interpolator.

I build BatchMark, an iPhone app for finishing photos in batches, so resize-to-a-max-edge is a step I think about a lot. What follows is a teaching version of a pipeline I'd use: measure the photo, scale it with Core Image's Lanczos filter when it is too large, and write a JPEG. It is not the app's source.

The rule is one number

Pick a maximum long edge, in pixels — 2000 is a common web size; 1600 or 3000 are equally fine — and apply it to every photo in the set. A 4000×3000 photo becomes 2000×1500. A 3000×4000 photo becomes 1500×2000. A photo that is already 1200×1800 is left alone. The aspect ratio does not change, and you never scale up.

Scaling up would make a larger file with no new detail. For listings and email, that is wasted bytes and a slightly softer picture.

Don't use the UIImage-into-a-small-rect shortcut for final output

The shortest code is to draw a UIImage into a UIGraphicsImageRenderer whose size is the target. It works, and for a thumbnail on screen it is often enough. For a batch you will actually upload, I would not start there.

UIImage drawing uses a general-purpose interpolator, and the renderer's default scale follows the screen (2× or 3×), which is a common way to accidentally produce a bitmap two or three times larger than you asked for. You can fix the scale by setting format.scale = 1, as I would in any export path. You cannot, from that API, ask for a Lanczos resample.

Core Image's CILanczosScaleTransform is the filter I'd use for a high-quality downsample. Lanczos is a standard choice for shrinking photos: it keeps edges cleaner than a cheap bilinear resize.

Load the image already oriented

A phone photo may be stored on its side with an orientation flag. If you ignore that, a portrait picture exports as a landscape bitmap with the subject on its side, and your "long edge" will be the wrong edge.

CIImage can apply that orientation as it loads:

import CoreImage
import CoreImage.CIFilterBuiltins

enum ResizeError: Error {
    case cannotLoad(URL)
    case cannotWrite(URL)
}

func loadOrientedImage(from url: URL) throws -> CIImage {
    let options: [CIImageOption: Any] = [.applyOrientationProperty: true]
    guard let image = CIImage(contentsOf: url, options: options) else {
        throw ResizeError.cannotLoad(url)
    }
    return image
}
Enter fullscreen mode Exit fullscreen mode

UIImage does this for you when you draw it; CIImage does not, unless you ask. Ask.

Scale, then write

Compute a single scale factor from the long edge, and only apply the filter when the photo is actually larger than the cap.

struct LongEdgeResize {
    var maxEdge: Int = 2000
    var jpegQuality: CGFloat = 0.85

    func scaleFactor(for size: CGSize) -> CGFloat {
        let longest = max(size.width, size.height)
        guard longest > CGFloat(maxEdge) else { return 1 }
        return CGFloat(maxEdge) / longest
    }

    /// Shift a possibly fractional extent so the bitmap starts at (0, 0).
    func normalized(_ image: CIImage) -> CIImage {
        let integral = image.extent.integral
        return image.transformed(
            by: CGAffineTransform(
                translationX: -integral.origin.x,
                y: -integral.origin.y
            )
        ).cropped(to: CGRect(origin: .zero, size: integral.size))
    }

    func resize(from source: URL, to destination: URL) throws {
        var image = try loadOrientedImage(from: source)
        let scale = scaleFactor(for: image.extent.size)

        if scale < 1 {
            let filter = CIFilter.lanczosScaleTransform()
            filter.inputImage = image
            filter.scale = Float(scale)
            filter.aspectRatio = 1
            guard let output = filter.outputImage else {
                throw ResizeError.cannotLoad(source)
            }
            image = output
        }

        image = normalized(image)

        let context = CIContext(options: [.useSoftwareRenderer: false])
        let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
        let quality: [CIImageRepresentationOption: Any] = [
            kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: jpegQuality
        ]

        guard let data = context.jpegRepresentation(
            of: image,
            colorSpace: colorSpace,
            options: quality
        ) else {
            throw ResizeError.cannotWrite(destination)
        }

        try data.write(to: destination, options: .atomic)
    }
}
Enter fullscreen mode Exit fullscreen mode

A few details in that code are easy to skip and worth keeping:

Integral extents. After a scale, Core Image may give you a fractional extent. Rounding it, and shifting the origin to (0, 0), avoids a one-pixel smear at the edge and a surprising canvas size.

sRGB when the file is for the web. Shop platforms and email clients are happiest with a boring sRGB JPEG. If you leave the colour space implicit, you can get a file that looks right in Photos and slightly dull, or slightly neon, in a browser. This is not a full colour-management article; it is a default that saves arguments.

A quality around 0.8–0.9. I would not crank JPEG quality to 1.0 for this job. You have already discarded pixels by resizing; a sensible compression setting keeps the file small enough to send. The exact number is a taste. 0.85 is a reasonable place to start. Compare two or three photos from the batch at 0.7, 0.85 and 0.95 before you lock it in.

Don't decode 48 megapixels if you don't have to. CIImage(contentsOf:) is convenient, and it can still end up holding a very large buffer when the filter runs. For a batch of full-resolution iPhone photos, a kinder first step is to ask ImageIO for a decode that is slightly larger than the target long edge (for example 1.5×), then run Lanczos for the last step. ImageIO's thumbnail creation options are the right tool for that first decode — I would not draw a full-size UIImage just to measure or to shrink.

Apply the same cap to the whole batch

The value of this step is not the filter. It is that every photo in the set obeys the same rule. If you resize some images in Preview and leave others at camera size, a shop grid or a client folder will feel uneven, and some uploads will fail a "maximum dimension" check you thought you had already handled.

Keep the cap in one place. Log the input size, the output size, and a skip when no scale was needed, so a failed or surprising file is easy to find. And, as with any batch of bitmaps, do not start every resize at once. Two or three photos in flight is plenty.

What this does not do

It does not crop. It does not pad. If you also need a 4:5 or a square frame, that is a later step, and it should run on the already-sized file or on a consistent master, with a decision about whether to crop or to add bars. Mixing "make it 2000 pixels" and "make it square" into one vague "resize" is how subjects get cut off.

It also does not promise a file weight in megabytes. Long-edge caps control pixels. A busy, detailed photo will still compress to a larger JPEG than a photo of a white wall. If a platform also has a maximum file size, check the bytes after you write, and only then decide whether to lower the quality a little.

I use this kind of step whenever a set has to leave the phone and live somewhere smaller than a camera roll. The rule stays dull on purpose: one number, the same aspect, no invented pixels, and a downsample that doesn't throw the sharpness away.

Top comments (0)