Skip to content

Commit 9247e55

Browse files
emreocellclaude
andcommitted
feat(image_codec): add pure-Rust PNG encoder (encode_png / save_image)
- encode_png: 8-bit gray / gray+alpha / RGB / RGBA -> valid PNG using stored DEFLATE blocks (zero dependencies), with input validation - save_image: writes a [C, H, W] u8 Tensor to a PNG file - promote crc32/adler32 from the test module to shared helpers - tests: encode -> decode round trips for 1-4 channels, multi-block streams, invalid input, and save_image -> load_image Palette (PLTE/tRNS) and 16-bit decoding were already supported by decode_png and are covered by existing tests. Refs #4 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 3bc79e9 commit 9247e55

1 file changed

Lines changed: 168 additions & 20 deletions

File tree

‎crates/oxideon-core/src/image_codec.rs‎

Lines changed: 168 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
//! Pure-Rust PNG and JPEG (baseline and progressive) image decoders returning `[C, H, W]` [`Tensor`]s.
1+
//! Pure-Rust PNG and JPEG (baseline and progressive) image decoders returning `[C, H, W]` [`Tensor`]s, plus a PNG encoder.
22
//!
33
//! Zero external image crate dependencies: decodes PNG (including Adam7 interlacing; gray / RGB / palette / alpha, 1-16 bit, all 5 scanline filters,
44
//! stored + fixed Huffman + dynamic Huffman DEFLATE) and baseline DCT JPEG (`SOF0`) directly
5-
//! in `oxideon-core`.
5+
//! in `oxideon-core`. [`encode_png`] / [`save_image`] write 8-bit gray / gray+alpha / RGB / RGBA PNGs using stored DEFLATE blocks.
66
77
use std::path::Path;
88

99
use crate::backend::{CpuStorage, Storage};
10+
use crate::dtype::DType;
1011
use crate::error::{Error, Result};
1112
use crate::layout::Layout;
1213
use crate::tensor::Tensor;
@@ -1210,30 +1211,129 @@ pub fn load_image(path: impl AsRef<Path>) -> Result<Tensor> {
12101211
decode_image_tensor(&bytes)
12111212
}
12121213

1213-
#[cfg(test)]
1214-
mod tests {
1215-
use super::*;
1214+
// ---------------------------------------------------------------------------
1215+
// PNG encoder (stored DEFLATE blocks, no external dependencies)
1216+
// ---------------------------------------------------------------------------
12161217

1217-
fn crc32(data: &[u8]) -> u32 {
1218-
let mut c = 0xFFFF_FFFFu32;
1219-
for &b in data {
1220-
c ^= b as u32;
1221-
for _ in 0..8 {
1222-
let m = (c & 1).wrapping_neg();
1223-
c = (c >> 1) ^ (0xEDB8_8320 & m);
1224-
}
1218+
/// CRC-32 (IEEE 802.3, as used by PNG chunks).
1219+
fn crc32(data: &[u8]) -> u32 {
1220+
let mut c = 0xFFFF_FFFFu32;
1221+
for &b in data {
1222+
c ^= b as u32;
1223+
for _ in 0..8 {
1224+
let m = (c & 1).wrapping_neg();
1225+
c = (c >> 1) ^ (0xEDB8_8320 & m);
12251226
}
1226-
!c
12271227
}
1228+
!c
1229+
}
12281230

1229-
fn adler32(data: &[u8]) -> u32 {
1230-
let (mut s1, mut s2) = (1u32, 0u32);
1231-
for &b in data {
1232-
s1 = (s1 + b as u32) % 65521;
1233-
s2 = (s2 + s1) % 65521;
1231+
/// Adler-32 checksum (zlib trailer).
1232+
fn adler32(data: &[u8]) -> u32 {
1233+
let (mut s1, mut s2) = (1u32, 0u32);
1234+
for chunk in data.chunks(5552) {
1235+
for &b in chunk {
1236+
s1 += b as u32;
1237+
s2 += s1;
12341238
}
1235-
(s2 << 16) | s1
1239+
s1 %= 65521;
1240+
s2 %= 65521;
12361241
}
1242+
(s2 << 16) | s1
1243+
}
1244+
1245+
fn write_png_chunk(out: &mut Vec<u8>, ctype: &[u8; 4], data: &[u8]) {
1246+
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
1247+
let crc_start = out.len();
1248+
out.extend_from_slice(ctype);
1249+
out.extend_from_slice(data);
1250+
let crc = crc32(&out[crc_start..]);
1251+
out.extend_from_slice(&crc.to_be_bytes());
1252+
}
1253+
1254+
/// Encodes interleaved 8-bit pixels (`height * width * channels` bytes, row-major, HWC) into a PNG file.
1255+
///
1256+
/// `channels` selects the color type: 1 = grayscale, 2 = grayscale + alpha, 3 = RGB, 4 = RGBA.
1257+
/// The image data is wrapped in uncompressed (stored) DEFLATE blocks, so the output is valid and
1258+
/// round-trips through [`decode_png`] but is not size-optimized.
1259+
pub fn encode_png(pixels: &[u8], width: usize, height: usize, channels: usize) -> Result<Vec<u8>> {
1260+
let color_type = match channels {
1261+
1 => 0u8,
1262+
2 => 4,
1263+
3 => 2,
1264+
4 => 6,
1265+
_ => return Err(Error::Msg(format!("encode_png: unsupported channel count {channels} (expected 1, 2, 3 or 4)"))),
1266+
};
1267+
if width == 0 || height == 0 {
1268+
return Err(Error::Msg(format!("encode_png: image dimensions must be non-zero, got {width}x{height}")));
1269+
}
1270+
if width > u32::MAX as usize || height > u32::MAX as usize {
1271+
return Err(Error::Msg(format!("encode_png: image dimensions {width}x{height} exceed the PNG limit")));
1272+
}
1273+
let row_bytes = width
1274+
.checked_mul(channels)
1275+
.ok_or_else(|| Error::Msg("encode_png: image size overflow".into()))?;
1276+
let expected = row_bytes
1277+
.checked_mul(height)
1278+
.ok_or_else(|| Error::Msg("encode_png: image size overflow".into()))?;
1279+
if pixels.len() != expected {
1280+
return Err(Error::Msg(format!(
1281+
"encode_png: expected {expected} bytes for {width}x{height}x{channels}, got {}",
1282+
pixels.len()
1283+
)));
1284+
}
1285+
1286+
// Scanlines: filter type 0 (None) followed by the row bytes.
1287+
let mut raw = Vec::with_capacity(expected + height);
1288+
for row in pixels.chunks_exact(row_bytes) {
1289+
raw.push(0);
1290+
raw.extend_from_slice(row);
1291+
}
1292+
1293+
// zlib stream made of stored blocks (max 65535 bytes each).
1294+
let mut zlib = Vec::with_capacity(raw.len() + raw.len() / 65535 * 5 + 11);
1295+
zlib.extend_from_slice(&[0x78, 0x01]);
1296+
let mut blocks = raw.chunks(65535).peekable();
1297+
while let Some(block) = blocks.next() {
1298+
zlib.push(u8::from(blocks.peek().is_none())); // BFINAL, BTYPE = 00 (stored)
1299+
let len = block.len() as u16;
1300+
zlib.extend_from_slice(&len.to_le_bytes());
1301+
zlib.extend_from_slice(&(!len).to_le_bytes());
1302+
zlib.extend_from_slice(block);
1303+
}
1304+
zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
1305+
1306+
let mut png = Vec::with_capacity(zlib.len() + 64);
1307+
png.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);
1308+
let mut ihdr = Vec::with_capacity(13);
1309+
ihdr.extend_from_slice(&(width as u32).to_be_bytes());
1310+
ihdr.extend_from_slice(&(height as u32).to_be_bytes());
1311+
ihdr.extend_from_slice(&[8, color_type, 0, 0, 0]);
1312+
write_png_chunk(&mut png, b"IHDR", &ihdr);
1313+
write_png_chunk(&mut png, b"IDAT", &zlib);
1314+
write_png_chunk(&mut png, b"IEND", &[]);
1315+
Ok(png)
1316+
}
1317+
1318+
/// Writes a `[C, H, W]` `u8` [`Tensor`] (1-4 channels) to `path` as a PNG file.
1319+
pub fn save_image(tensor: &Tensor, path: impl AsRef<Path>) -> Result<()> {
1320+
if tensor.dtype() != DType::U8 {
1321+
return Err(Error::Msg(format!("save_image: expected a u8 tensor, got {:?}", tensor.dtype())));
1322+
}
1323+
let shape = tensor.shape();
1324+
if shape.len() != 3 {
1325+
return Err(Error::Msg(format!("save_image: expected a [C, H, W] tensor, got shape {shape:?}")));
1326+
}
1327+
let (c, h, w) = (shape[0], shape[1], shape[2]);
1328+
let hwc = tensor.permute(&[1, 2, 0])?.contiguous()?.to_vec::<u8>()?;
1329+
let png = encode_png(&hwc, w, h, c)?;
1330+
std::fs::write(path.as_ref(), png)
1331+
.map_err(|e| Error::Msg(format!("save_image '{}': {e}", path.as_ref().display())))
1332+
}
1333+
1334+
#[cfg(test)]
1335+
mod tests {
1336+
use super::*;
12371337

12381338
fn png_chunk(ctype: &[u8; 4], data: &[u8], out: &mut Vec<u8>) {
12391339
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
@@ -1330,4 +1430,52 @@ mod tests {
13301430
// Channel 2 (B): [0, 0, 255, 0]
13311431
assert_eq!(&v[8..12], &[0, 0, 255, 0]);
13321432
}
1433+
1434+
#[test]
1435+
fn encode_png_round_trips_all_channel_counts() {
1436+
for channels in 1..=4usize {
1437+
let (w, h) = (5, 3);
1438+
let px: Vec<u8> = (0..w * h * channels).map(|i| (i * 37 % 256) as u8).collect();
1439+
let png = encode_png(&px, w, h, channels).unwrap();
1440+
assert_eq!(&png[..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
1441+
let (out, ow, oh, oc) = decode_png(&png).unwrap();
1442+
assert_eq!((ow, oh, oc), (w, h, channels));
1443+
assert_eq!(out, px, "channels = {channels}");
1444+
}
1445+
}
1446+
1447+
#[test]
1448+
fn encode_png_splits_large_images_into_multiple_stored_blocks() {
1449+
// 200 * 200 * 3 + 200 filter bytes = 120_200 raw bytes -> two stored blocks
1450+
let (w, h) = (200, 200);
1451+
let px: Vec<u8> = (0..w * h * 3).map(|i| (i % 251) as u8).collect();
1452+
let png = encode_png(&px, w, h, 3).unwrap();
1453+
let (out, ow, oh, oc) = decode_png(&png).unwrap();
1454+
assert_eq!((ow, oh, oc), (w, h, 3));
1455+
assert_eq!(out, px);
1456+
}
1457+
1458+
#[test]
1459+
fn encode_png_rejects_invalid_input() {
1460+
assert!(encode_png(&[0; 3], 1, 1, 5).is_err());
1461+
assert!(encode_png(&[0; 3], 1, 1, 0).is_err());
1462+
assert!(encode_png(&[], 0, 1, 3).is_err());
1463+
assert!(encode_png(&[0; 5], 1, 2, 3).is_err(), "buffer length must match width*height*channels");
1464+
}
1465+
1466+
#[test]
1467+
fn save_image_writes_chw_tensor_that_load_image_reads_back() {
1468+
let (c, h, w) = (3, 2, 4);
1469+
let chw: Vec<u8> = (0..c * h * w).map(|i| (i * 11) as u8).collect();
1470+
let t = Tensor::from_storage(Storage::new_cpu(CpuStorage::U8(chw.clone())), Layout::contiguous(vec![c, h, w]));
1471+
let path = std::env::temp_dir().join(format!("oxideon_save_image_{}.png", std::process::id()));
1472+
save_image(&t, &path).unwrap();
1473+
let back = load_image(&path).unwrap();
1474+
let _ = std::fs::remove_file(&path);
1475+
assert_eq!(back.shape(), &[c, h, w]);
1476+
assert_eq!(back.to_vec::<u8>().unwrap(), chw);
1477+
1478+
let bad = Tensor::from_storage(Storage::new_cpu(CpuStorage::U8(vec![0; 4])), Layout::contiguous(vec![2, 2]));
1479+
assert!(save_image(&bad, &path).is_err());
1480+
}
13331481
}

0 commit comments

Comments
 (0)