truss-image 0.23.0

Image toolkit with a shared Rust core across the CLI, HTTP server, and WASM demo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::{ColorType, GenericImageView, ImageEncoder, ImageReader, Rgba, RgbaImage};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

fn temp_file_path(name: &str) -> PathBuf {
    let unique = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("current time")
        .as_nanos();
    std::env::temp_dir().join(format!("truss-cli-pixel-{name}-{unique}.bin"))
}

/// Create a 4x2 PNG where left half is red and right half is blue.
fn create_red_blue_4x2_png() -> Vec<u8> {
    let mut img = RgbaImage::new(4, 2);
    let red = Rgba([255, 0, 0, 255]);
    let blue = Rgba([0, 0, 255, 255]);
    for y in 0..2 {
        for x in 0..4 {
            if x < 2 {
                img.put_pixel(x, y, red);
            } else {
                img.put_pixel(x, y, blue);
            }
        }
    }
    let mut bytes = Vec::new();
    let encoder = PngEncoder::new(&mut bytes);
    encoder
        .write_image(&img, 4, 2, ColorType::Rgba8.into())
        .expect("encode png");
    bytes
}

/// Create a solid-color 4x2 PNG with all pixels blue.
fn create_solid_blue_4x2_png() -> Vec<u8> {
    let img = RgbaImage::from_pixel(4, 2, Rgba([0, 0, 255, 255]));
    let mut bytes = Vec::new();
    let encoder = PngEncoder::new(&mut bytes);
    encoder
        .write_image(&img, 4, 2, ColorType::Rgba8.into())
        .expect("encode png");
    bytes
}

/// Create a 2x2 solid green PNG.
fn create_solid_green_2x2_png() -> Vec<u8> {
    let img = RgbaImage::from_pixel(2, 2, Rgba([0, 255, 0, 255]));
    let mut bytes = Vec::new();
    let encoder = PngEncoder::new(&mut bytes);
    encoder
        .write_image(&img, 2, 2, ColorType::Rgba8.into())
        .expect("encode png");
    bytes
}

/// Create a 4x2 JPEG with EXIF Orientation=6 (90° CW rotation).
fn create_4x2_jpeg_with_orientation6() -> Vec<u8> {
    use image::{Rgb, RgbImage};
    let img = RgbImage::from_pixel(4, 2, Rgb([10, 20, 30]));
    let mut bytes = Vec::new();
    let mut encoder = JpegEncoder::new_with_quality(&mut bytes, 90);
    let exif = vec![
        0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x01, 0x03, 0x00, 0x01,
        0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    ];
    encoder
        .set_exif_metadata(exif)
        .expect("set jpeg exif metadata");
    encoder
        .write_image(&img, 4, 2, ColorType::Rgb8.into())
        .expect("encode jpeg");
    bytes
}

/// Create a 4x2 JPEG with EXIF Orientation=1 (no rotation).
fn create_4x2_jpeg_with_orientation1() -> Vec<u8> {
    use image::{Rgb, RgbImage};
    let img = RgbImage::from_pixel(4, 2, Rgb([10, 20, 30]));
    let mut bytes = Vec::new();
    let mut encoder = JpegEncoder::new_with_quality(&mut bytes, 90);
    let exif = vec![
        0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x01, 0x03, 0x00, 0x01,
        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    ];
    encoder
        .set_exif_metadata(exif)
        .expect("set jpeg exif metadata");
    encoder
        .write_image(&img, 4, 2, ColorType::Rgb8.into())
        .expect("encode jpeg");
    bytes
}

// ---------------------------------------------------------------------------
// Test 1: fit=cover + position pixel verification
// ---------------------------------------------------------------------------

#[test]
fn fit_cover_position_left_keeps_red() {
    let input_path = temp_file_path("cover-left-in").with_extension("png");
    let output_path = temp_file_path("cover-left-out").with_extension("png");
    fs::write(&input_path, create_red_blue_4x2_png()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--width")
        .arg("2")
        .arg("--height")
        .arg("2")
        .arg("--fit")
        .arg("cover")
        .arg("--position")
        .arg("left")
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");

    let result = image::open(&output_path).expect("open output").to_rgba8();

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    // With position=left on a 4x2→2x2 cover crop, the left portion is kept,
    // so pixel (0,0) should be red.
    let px = result.get_pixel(0, 0);
    assert!(
        px[0] > 200 && px[1] < 50 && px[2] < 50,
        "expected red-ish pixel at (0,0), got {px:?}"
    );
}

#[test]
fn fit_cover_position_right_keeps_blue() {
    let input_path = temp_file_path("cover-right-in").with_extension("png");
    let output_path = temp_file_path("cover-right-out").with_extension("png");
    fs::write(&input_path, create_red_blue_4x2_png()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--width")
        .arg("2")
        .arg("--height")
        .arg("2")
        .arg("--fit")
        .arg("cover")
        .arg("--position")
        .arg("right")
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");

    let result = image::open(&output_path).expect("open output").to_rgba8();

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    // With position=right on a 4x2→2x2 cover crop, the right portion is kept,
    // so pixel (0,0) should be blue.
    let px = result.get_pixel(0, 0);
    assert!(
        px[0] < 50 && px[1] < 50 && px[2] > 200,
        "expected blue-ish pixel at (0,0), got {px:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 2: fit=contain + background padding color
// ---------------------------------------------------------------------------

#[test]
fn fit_contain_background_padding_color() {
    let input_path = temp_file_path("contain-bg-in").with_extension("png");
    let output_path = temp_file_path("contain-bg-out").with_extension("png");
    fs::write(&input_path, create_solid_blue_4x2_png()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--width")
        .arg("4")
        .arg("--height")
        .arg("4")
        .arg("--fit")
        .arg("contain")
        .arg("--background")
        .arg("ff0000")
        .arg("--format")
        .arg("png")
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");

    let result = image::open(&output_path).expect("open output").to_rgba8();

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    // Output should be 4x4.
    assert_eq!(
        result.dimensions(),
        (4, 4),
        "expected 4x4 output, got {:?}",
        result.dimensions()
    );

    // Pixel at (0,0) should be red padding (top row).
    let top_left = result.get_pixel(0, 0);
    assert!(
        top_left[0] > 200 && top_left[1] < 50 && top_left[2] < 50,
        "expected red padding at (0,0), got {top_left:?}"
    );

    // Pixel at (0,3) should be red padding (bottom row).
    let bottom_left = result.get_pixel(0, 3);
    assert!(
        bottom_left[0] > 200 && bottom_left[1] < 50 && bottom_left[2] < 50,
        "expected red padding at (0,3), got {bottom_left:?}"
    );

    // Pixel at (0,1) should be blue (image content, centered vertically).
    let content = result.get_pixel(0, 1);
    assert!(
        content[0] < 50 && content[1] < 50 && content[2] > 200,
        "expected blue content at (0,1), got {content:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 3: --no-auto-orient verification
// ---------------------------------------------------------------------------

#[test]
fn auto_orient_rotates_dimensions() {
    let input_path = temp_file_path("orient-auto-in").with_extension("jpg");
    let output_path = temp_file_path("orient-auto-out").with_extension("png");
    fs::write(&input_path, create_4x2_jpeg_with_orientation6()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--format")
        .arg("png")
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");

    let result = ImageReader::open(&output_path)
        .expect("open output")
        .decode()
        .expect("decode output");

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    // Default auto-orient with orientation=6 (90° CW): 4x2 becomes 2x4.
    assert_eq!(
        result.dimensions(),
        (2, 4),
        "auto-orient should rotate 4x2 to 2x4, got {:?}",
        result.dimensions()
    );
}

#[test]
fn no_auto_orient_preserves_dimensions() {
    let input_path = temp_file_path("orient-no-in").with_extension("jpg");
    let output_path = temp_file_path("orient-no-out").with_extension("png");
    fs::write(&input_path, create_4x2_jpeg_with_orientation6()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--format")
        .arg("png")
        .arg("--no-auto-orient")
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");

    let result = ImageReader::open(&output_path)
        .expect("open output")
        .decode()
        .expect("decode output");

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    // With --no-auto-orient, original 4x2 dimensions are preserved.
    assert_eq!(
        result.dimensions(),
        (4, 2),
        "--no-auto-orient should keep 4x2, got {:?}",
        result.dimensions()
    );
}

// ---------------------------------------------------------------------------
// Test 4: --keep-metadata --format webp --quality carries EXIF into the container
// ---------------------------------------------------------------------------

#[test]
fn keep_metadata_webp_preserves_exif_without_warning() {
    let input_path = temp_file_path("warn-meta-in").with_extension("jpg");
    let output_path = temp_file_path("warn-meta-out").with_extension("webp");
    fs::write(&input_path, create_4x2_jpeg_with_orientation1()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--keep-metadata")
        .arg("--format")
        .arg("webp")
        .arg("--quality")
        .arg("80")
        .output()
        .expect("run truss convert");

    let encoded = fs::read(&output_path).unwrap_or_default();

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);

    assert!(
        output.status.success(),
        "expected exit code 0, got {output:?}"
    );

    // Lossy WebP used to drop EXIF and warn about it; the chunk is written now.
    assert!(
        encoded.windows(4).any(|window| window == b"EXIF"),
        "expected an EXIF chunk in the WebP container"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.to_lowercase().contains("warning"),
        "nothing was dropped, so nothing should warn; got: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// Test 5: fit=inside adds no padding, and enlargement is a separate switch
// ---------------------------------------------------------------------------

/// Runs `truss convert` on a 2x2 green PNG into a 4x4 box and returns the output pixels.
fn resize_green_2x2_into_4x4(label: &str, extra: &[&str]) -> image::RgbaImage {
    let input_path = temp_file_path(&format!("{label}-in")).with_extension("png");
    let output_path = temp_file_path(&format!("{label}-out")).with_extension("png");
    fs::write(&input_path, create_solid_green_2x2_png()).expect("write input");

    let output = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&input_path)
        .arg("-o")
        .arg(&output_path)
        .arg("--width")
        .arg("4")
        .arg("--height")
        .arg("4")
        .arg("--background")
        .arg("ff0000")
        .arg("--format")
        .arg("png")
        .args(extra)
        .output()
        .expect("run truss convert");

    assert!(output.status.success(), "{output:?}");
    let result = image::open(&output_path).expect("open output").to_rgba8();

    let _ = fs::remove_file(&input_path);
    let _ = fs::remove_file(&output_path);
    result
}

#[test]
fn fit_inside_adds_no_padding() {
    // A 2x2 square in a 4x4 box has the same aspect ratio, so inside fills it exactly and
    // there is nothing to pad. The red background must not appear anywhere.
    let result = resize_green_2x2_into_4x4("inside-nopad", &["--fit", "inside"]);

    assert_eq!(result.dimensions(), (4, 4));
    for (x, y, pixel) in result.enumerate_pixels() {
        assert!(
            pixel[1] > 200 && pixel[0] < 50,
            "pixel ({x},{y}) should be green content, not padding: {pixel:?}"
        );
    }
}

#[test]
fn fit_inside_with_without_enlargement_keeps_the_source_size() {
    // Enlargement is now its own switch rather than part of the fit mode, and turning it
    // off returns the source size rather than a padded box.
    let result =
        resize_green_2x2_into_4x4("inside-noup", &["--fit", "inside", "--without-enlargement"]);

    assert_eq!(result.dimensions(), (2, 2));
    let pixel = result.get_pixel(0, 0);
    assert!(
        pixel[1] > 200 && pixel[0] < 50,
        "expected untouched green content, got {pixel:?}"
    );
}

#[test]
fn fit_contain_with_without_enlargement_pads_around_the_source() {
    // Contain still reports the requested box, so this is the combination that produces the
    // padded 4x4 with 2x2 content that `inside` used to give on its own.
    let result = resize_green_2x2_into_4x4(
        "contain-noup",
        &["--fit", "contain", "--without-enlargement"],
    );

    assert_eq!(result.dimensions(), (4, 4));

    let corner = result.get_pixel(0, 0);
    assert!(
        corner[0] > 200 && corner[1] < 50 && corner[2] < 50,
        "expected red padding at corner (0,0), got {corner:?}"
    );

    let center = result.get_pixel(1, 1);
    assert!(
        center[1] > 200 && center[0] < 50 && center[2] < 50,
        "expected green content at center, got {center:?}"
    );
}

/// The compiled binary decodes an AVIF.
///
/// This ran through the library and never through the binary until it did, and the binary is
/// where the thread the process starts on decides how much stack the decoder gets: one
/// megabyte on Windows, which an AV1 decode does not fit in a build without optimizations. The
/// requirement does not depend on the size of the picture, since what wants the room is the
/// decoder's own working set, so the smallest image reaches it.
#[cfg(feature = "avif")]
#[test]
fn convert_decodes_an_avif_through_the_binary() {
    let source = temp_file_path("avif-source").with_extension("png");
    let avif = temp_file_path("avif-middle").with_extension("avif");
    let output = temp_file_path("avif-output").with_extension("png");
    fs::write(&source, create_red_blue_4x2_png()).expect("write png source");

    let to_avif = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&source)
        .arg("-o")
        .arg(&avif)
        .output()
        .expect("run truss convert to avif");
    assert!(to_avif.status.success(), "{to_avif:?}");

    let from_avif = Command::new(env!("CARGO_BIN_EXE_truss"))
        .arg(&avif)
        .arg("-o")
        .arg(&output)
        .output()
        .expect("run truss convert from avif");

    let decoded = fs::read(&output).ok();
    let _ = fs::remove_file(&source);
    let _ = fs::remove_file(&avif);
    let _ = fs::remove_file(&output);

    assert!(from_avif.status.success(), "{from_avif:?}");
    let decoded = ImageReader::new(std::io::Cursor::new(decoded.expect("the png was written")))
        .with_guessed_format()
        .expect("guess the output format")
        .decode()
        .expect("decode the output");
    assert_eq!(decoded.dimensions(), (4, 2));
}