Test iOS bilinear resizing: pixel centers and clamped edges

Test iOS bilinear resizing: pixel centers and clamped edges

You finish implementing image editing on Windows, then send the same image to a cloud Mac for resizing—and the preview shows a half-pixel shift or a dark fringe. Before adjusting compression quality, reduce the image to a grayscale matrix small enough to calculate by hand. Check that coordinate mapping, neighboring samples, and edge handling all follow the same conventions. The Swift test fixture below runs directly in a remote terminal, with no desktop screenshots or real user photos required.

Define the coordinate contract first

Here, source pixel centers have integer coordinates, with (0, 0) at the center of the top-left pixel. To map target column x back to the source image, use sx = (x + 0.5) × source width ÷ target width − 0.5; apply the same formula vertically. This maps target pixel centers across the source image’s full extent rather than forcing the first and last pixel centers to coincide.

When upscaling, mapped coordinates can fall slightly below zero. In this implementation, clamp the continuous coordinate to the valid range of pixel centers before calculating neighboring pixels and weights. Do not truncate to an integer first and then calculate weights from the original negative coordinate.

Half-pixel mapping is not the only valid convention. Aligning endpoints can also work, but the reference implementation, production code, and expected values must all use the same rule. Calling an operation “bilinear” is not enough to define its output.

This test handles only finite, single-channel values. Image decoding, orientation correction, and color-space conversion should happen before data reaches the sampler, so they cannot mask coordinate errors.

Build an executable fixture on a cloud Mac

First, run xcrun --find swift in the terminal to confirm that the toolchain is available, then save the following as BilinearCheck.swift. Arrays use row-major order, with y × width + x as the sole indexing rule. The example explicitly limits the number of input and output elements so that invalid dimensions do not trigger a large allocation first.

import Foundation

func resize(
    _ source: [Double],
    width: Int,
    height: Int,
    toWidth: Int,
    toHeight: Int
) -> [Double] {
    let limit = 1_000_000
    precondition(width > 0 && height > 0)
    precondition(toWidth > 0 && toHeight > 0)
    precondition(width <= limit / height)
    precondition(toWidth <= limit / toHeight)
    precondition(source.count == width * height)
    precondition(source.allSatisfy { $0.isFinite })

    func pixel(_ x: Int, _ y: Int) -> Double {
        source[y * width + x]
    }

    var output = [Double]()
    output.reserveCapacity(toWidth * toHeight)

    for y in 0..<toHeight {
        let rawY = (Double(y) + 0.5)
            * Double(height) / Double(toHeight) - 0.5
        let sy = min(max(rawY, 0), Double(height - 1))
        let y0 = Int(sy.rounded(.down))
        let y1 = min(y0 + 1, height - 1)
        let fy = sy - Double(y0)

        for x in 0..<toWidth {
            let rawX = (Double(x) + 0.5)
                * Double(width) / Double(toWidth) - 0.5
            let sx = min(max(rawX, 0), Double(width - 1))
            let x0 = Int(sx.rounded(.down))
            let x1 = min(x0 + 1, width - 1)
            let fx = sx - Double(x0)
            let top = pixel(x0, y0) * (1 - fx)
                + pixel(x1, y0) * fx
            let bottom = pixel(x0, y1) * (1 - fx)
                + pixel(x1, y1) * fx
            output.append(top * (1 - fy) + bottom * fy)
        }
    }
    return output
}

func expect(_ actual: [Double], _ expected: [Double]) {
    precondition(actual.count == expected.count)
    precondition(zip(actual, expected).allSatisfy {
        abs($0.0 - $0.1) <= 1e-12
    })
}

expect(
    resize([0, 1], width: 2, height: 1, toWidth: 4, toHeight: 1),
    [0, 0.25, 0.75, 1]
)
expect(
    resize([0, 1, 2, 3], width: 2, height: 2, toWidth: 1, toHeight: 1),
    [1.5]
)
let rectangle: [Double] = [0, 1, 2, 10, 11, 12]
expect(
    resize(rectangle, width: 3, height: 2, toWidth: 3, toHeight: 2),
    rectangle
)
expect(
    resize([0.3], width: 1, height: 1, toWidth: 3, toHeight: 2),
    Array(repeating: 0.3, count: 6)
)

Run xcrun swift BilinearCheck.swift. Successful tests produce no output; a failed assertion terminates the process with a nonzero exit status. Your pipeline must preserve that status. The preconditions in this example are suitable for internal tests, but a production interface that accepts external images should return an identifiable error instead of terminating the application.

Pinpoint errors with asymmetric data

The first case expands two pixels into four. The inner values should be 0.25 and 0.75, while the endpoints retain their original values. If edge values fall below zero or exceed one, first check whether weights were calculated before clamping.

The second case reduces four values to one. The target center maps to the center of the source image, producing the mean of the four samples. This verifies only that particular sampling position; it does not establish that large reductions are equivalent to area averaging.

The third case deliberately uses three columns and two rows, with every value in the second row increased by ten. A square checkerboard can hide swapped width and height, whereas an asymmetric matrix exposes row-stride errors directly. Once identity resizing passes, add resizing combinations involving single rows, single columns, and odd dimensions.

The fourth case checks a single-pixel input: every output must retain the same constant value. Add rejection tests for zero dimensions, mismatched element counts, and non-finite inputs as well. Run these through a production interface with catchable errors, not by directly calling fixture functions that terminate the process.

Validate color and transparency separately

Treat the values above as linear intensities, not unconverted image bytes. Averaging equal parts linear black and white gives 0.5, but after encoding into a nonlinear color space, the byte value does not necessarily lie at the numeric midpoint. Comparing results from different color spaces byte for byte can cause a correct implementation to fail a test.

For transparent images, you must also specify whether alpha is premultiplied. Interpolating fully transparent red and opaque blue directly as independent RGB channels can introduce red at an edge where it should not be visible. Follow the production pipeline’s premultiplication convention, then check the result composited over both light and dark backgrounds.

Bilinear interpolation is not, by itself, an anti-aliasing filter either. When reducing an image substantially, fine lines and checkerboard patterns can alias. That is a downsampling-filter issue, not something to fix by changing the coordinate formula.

Add regression coverage and record failing coordinates

When integrating these tests into your project, feed the reference function and the production sampler the same small matrices, using the same agreed edge-handling policy. Failure records should include at least the input dimensions, output dimensions, first differing coordinate, expected value, and actual value. There is no need to upload complete application images.

First, validate the reference function against hand-calculated values. Then use it to check a batch of dimension combinations, avoiding a situation where both implementations share the same incorrect formula. For integer output, define rounding and saturation rules separately. Set floating-point tolerances according to channel precision rather than reusing the example’s double-precision threshold unchanged.

Finally, keep a set of synthetic image fixtures that have actually passed through decoding, covering opaque gradients, transparent edges, and single-pixel lines. Matrix tests explain numerical discrepancies; image tests check the decoding and compositing pipeline. Both layers must pass independently before you can consider the resizing feature ready to ship.

Frequently asked questions

Is half-pixel mapping required for bilinear resizing?

No. Half-pixel mapping and aligned endpoints are different coordinate conventions. This guide uses half-pixel mapping; the implementation and reference fixtures must use the same convention.

Do passing grayscale tests prove transparent color images are correct?

No. Test the color space, premultiplied alpha, and channel layout separately. Check transparent edges composited over different backgrounds rather than comparing hidden RGB values alone.

Choose a cloud Mac for your next project

Need a macOS GUI or command line? Start by choosing a model, location, and billing period that fit your project. After payment, provisioning begins. Check the console for real-time availability.

Choose a cloud Mac plan

Pick your project, then launch a cloud Mac

Choose a model, location, and billing period. Provisioning begins after payment. Check the console for real-time availability.