A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
//! Pure-Rust fast lossless RGBA8 PNG encoder & base64 data-URL utilities
//! for 64×64 layer/mask thumbnails, `.ink` previews, and timelapse keyframes.
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{Read, Write};
const PNG_SIG: &[u8; 8] = &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) -> Result<(), String> {
let len = u32::try_from(data.len()).map_err(|_| "PNG chunk exceeds 4 GB".to_string())?;
out.extend_from_slice(&len.to_be_bytes());
out.extend_from_slice(chunk_type);
out.extend_from_slice(data);
let mut hasher = crc32fast::Hasher::new();
hasher.update(chunk_type);
hasher.update(data);
out.extend_from_slice(&hasher.finalize().to_be_bytes());
Ok(())
}
/// Encodes an RGBA8 image buffer into a valid lossless PNG using Sub row filtering + fast zlib.
pub fn encode_rgba8_to_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
if width == 0 || height == 0 || width > 16384 || height > 16384 {
return Err(format!("Invalid PNG dimensions: {width}x{height}"));
}
let row_bytes = (width as usize)
.checked_mul(4)
.ok_or_else(|| "PNG row stride overflow".to_string())?;
let expected = row_bytes
.checked_mul(height as usize)
.ok_or_else(|| "PNG buffer size overflow".to_string())?;
if rgba.len() != expected {
return Err(format!(
"PNG RGBA buffer mismatch: expected {expected}, got {}",
rgba.len()
));
}
let mut encoder = ZlibEncoder::new(Vec::with_capacity(expected / 4 + 128), Compression::fast());
let mut filtered_row = vec![0u8; 1 + row_bytes];
filtered_row[0] = 1; // PNG Sub filter (bpp = 4)
for y in 0..(height as usize) {
let row = &rgba[y * row_bytes..(y + 1) * row_bytes];
for i in 0..row_bytes {
let left = if i >= 4 { row[i - 4] } else { 0 };
filtered_row[1 + i] = row[i].wrapping_sub(left);
}
encoder
.write_all(&filtered_row)
.map_err(|e| format!("PNG zlib write error: {e}"))?;
}
let idat = encoder
.finish()
.map_err(|e| format!("PNG zlib finish error: {e}"))?;
let mut out = Vec::with_capacity(64 + idat.len());
out.extend_from_slice(PNG_SIG);
let mut ihdr = [0u8; 13];
ihdr[0..4].copy_from_slice(&width.to_be_bytes());
ihdr[4..8].copy_from_slice(&height.to_be_bytes());
ihdr[8] = 8; // 8-bit depth
ihdr[9] = 6; // RGBA
ihdr[10] = 0; // deflate
ihdr[11] = 0; // adaptive filtering
ihdr[12] = 0; // non-interlaced
write_png_chunk(&mut out, b"IHDR", &ihdr)?;
write_png_chunk(&mut out, b"IDAT", &idat)?;
write_png_chunk(&mut out, b"IEND", &[])?;
Ok(out)
}
/// Standard RFC-4648 Base64 encoder for inline `data:image/png;base64,...` thumbnails.
pub fn to_base64(data: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = chunk[0];
let b1 = if chunk.len() > 1 { chunk[1] } else { 0 };
let b2 = if chunk.len() > 2 { chunk[2] } else { 0 };
out.push(TABLE[(b0 >> 2) as usize] as char);
out.push(TABLE[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
if chunk.len() > 1 {
out.push(TABLE[(((b1 & 0x0F) << 2) | (b2 >> 6)) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(TABLE[(b2 & 0x3F) as usize] as char);
} else {
out.push('=');
}
}
out
}
pub fn png_bytes_to_data_url(png: &[u8]) -> String {
if png.is_empty() {
return String::new();
}
format!("data:image/png;base64,{}", to_base64(png))
}
#[inline]
fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
let ai = a as i32;
let bi = b as i32;
let ci = c as i32;
let p = ai + bi - ci;
let pa = (p - ai).abs();
let pb = (p - bi).abs();
let pc = (p - ci).abs();
if pa <= pb && pa <= pc {
a
} else if pb <= pc {
b
} else {
c
}
}
/// Pure-Rust PNG decoder supporting non-interlaced 8-bit/16-bit Gray, RGB, Palette,
/// Gray+Alpha, and RGBA PNGs (all 5 PNG scanline filters) for brush tips & paper textures.
pub fn decode_png_rgba8(png: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
if png.len() < 33 || &png[0..8] != PNG_SIG {
return Err("Invalid PNG signature".to_string());
}
let mut pos = 8usize;
let mut width = 0u32;
let mut height = 0u32;
let mut bit_depth = 0u8;
let mut color_type = 0u8;
let mut interlace = 0u8;
let mut palette: Vec<[u8; 3]> = Vec::new();
let mut trns: Vec<u8> = Vec::new();
let mut idat: Vec<u8> = Vec::new();
while pos + 12 <= png.len() {
let len = u32::from_be_bytes([png[pos], png[pos + 1], png[pos + 2], png[pos + 3]]) as usize;
let ctype = &png[pos + 4..pos + 8];
let data_start = pos + 8;
let data_end = data_start
.checked_add(len)
.ok_or_else(|| "PNG chunk length overflow".to_string())?;
if data_end + 4 > png.len() {
return Err("Truncated PNG chunk".to_string());
}
let data = &png[data_start..data_end];
pos = data_end + 4;
match ctype {
b"IHDR" => {
if data.len() < 13 {
return Err("Invalid IHDR chunk".to_string());
}
width = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
height = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
bit_depth = data[8];
color_type = data[9];
interlace = data[12];
}
b"PLTE" => {
palette.clear();
for chunk in data.chunks_exact(3) {
palette.push([chunk[0], chunk[1], chunk[2]]);
}
}
b"tRNS" => {
trns.extend_from_slice(data);
}
b"IDAT" => {
idat.extend_from_slice(data);
}
b"IEND" => break,
_ => {}
}
}
if width == 0 || height == 0 || width > 8192 || height > 8192 {
return Err(format!("Unsupported PNG dimensions: {width}x{height}"));
}
if interlace != 0 {
return Err("Interlaced PNG is not supported for brush tips".to_string());
}
if bit_depth != 8 && bit_depth != 16 {
return Err(format!("Unsupported PNG bit depth: {bit_depth}"));
}
if color_type == 3 && bit_depth != 8 {
return Err(format!("Unsupported indexed PNG bit depth: {bit_depth}"));
}
let channels: usize = match color_type {
0 => 1, // Grayscale
2 => 3, // RGB
3 => 1, // Indexed Palette
4 => 2, // Grayscale + Alpha
6 => 4, // RGBA
_ => return Err(format!("Unsupported PNG color type: {color_type}")),
};
let bytes_per_sample = (bit_depth / 8) as usize;
let bpp = channels * bytes_per_sample;
let row_bytes = (width as usize) * bpp;
let expected_raw = (row_bytes + 1)
.checked_mul(height as usize)
.ok_or_else(|| "PNG buffer overflow".to_string())?;
let mut raw = Vec::with_capacity(expected_raw);
let max_decode = (expected_raw as u64).saturating_add(64);
let mut decoder = ZlibDecoder::new(idat.as_slice()).take(max_decode);
decoder
.read_to_end(&mut raw)
.map_err(|e| format!("PNG zlib decode error: {e}"))?;
if raw.len() < expected_raw {
return Err(format!(
"Truncated PNG image data: expected {expected_raw}, got {}",
raw.len()
));
}
// Unfilter scanlines
let mut prev_row = vec![0u8; row_bytes];
let mut cur_row = vec![0u8; row_bytes];
let mut rgba = vec![0u8; (width as usize) * (height as usize) * 4];
for y in 0..(height as usize) {
let src_off = y * (row_bytes + 1);
let filter = raw[src_off];
let src = &raw[src_off + 1..src_off + 1 + row_bytes];
for i in 0..row_bytes {
let left = if i >= bpp { cur_row[i - bpp] } else { 0 };
let up = prev_row[i];
let up_left = if i >= bpp { prev_row[i - bpp] } else { 0 };
cur_row[i] = match filter {
0 => src[i],
1 => src[i].wrapping_add(left),
2 => src[i].wrapping_add(up),
3 => src[i].wrapping_add((((left as u16) + (up as u16)) >> 1) as u8),
4 => src[i].wrapping_add(paeth_predictor(left, up, up_left)),
_ => return Err(format!("Unsupported PNG scanline filter: {filter}")),
};
}
let dst_row = y * (width as usize) * 4;
for x in 0..(width as usize) {
let p = x * bpp;
let d = dst_row + x * 4;
match (color_type, bit_depth) {
(6, 8) => {
rgba[d] = cur_row[p];
rgba[d + 1] = cur_row[p + 1];
rgba[d + 2] = cur_row[p + 2];
rgba[d + 3] = cur_row[p + 3];
}
(6, 16) => {
rgba[d] = cur_row[p];
rgba[d + 1] = cur_row[p + 2];
rgba[d + 2] = cur_row[p + 4];
rgba[d + 3] = cur_row[p + 6];
}
(2, 8) => {
rgba[d] = cur_row[p];
rgba[d + 1] = cur_row[p + 1];
rgba[d + 2] = cur_row[p + 2];
rgba[d + 3] = 255;
}
(2, 16) => {
rgba[d] = cur_row[p];
rgba[d + 1] = cur_row[p + 2];
rgba[d + 2] = cur_row[p + 4];
rgba[d + 3] = 255;
}
(4, 8) => {
let g = cur_row[p];
rgba[d] = g;
rgba[d + 1] = g;
rgba[d + 2] = g;
rgba[d + 3] = cur_row[p + 1];
}
(4, 16) => {
let g = cur_row[p];
rgba[d] = g;
rgba[d + 1] = g;
rgba[d + 2] = g;
rgba[d + 3] = cur_row[p + 2];
}
(0, 8) => {
let g = cur_row[p];
rgba[d] = g;
rgba[d + 1] = g;
rgba[d + 2] = g;
rgba[d + 3] = 255;
}
(0, 16) => {
let g = cur_row[p];
rgba[d] = g;
rgba[d + 1] = g;
rgba[d + 2] = g;
rgba[d + 3] = 255;
}
(3, 8) => {
let idx = cur_row[p] as usize;
let rgb = palette.get(idx).copied().unwrap_or([0, 0, 0]);
let a = trns.get(idx).copied().unwrap_or(255);
rgba[d] = rgb[0];
rgba[d + 1] = rgb[1];
rgba[d + 2] = rgb[2];
rgba[d + 3] = a;
}
_ => {
return Err(format!(
"Unsupported PNG color type/bit depth combination: {color_type}/{bit_depth}"
));
}
}
}
std::mem::swap(&mut prev_row, &mut cur_row);
}
Ok((width, height, rgba))
}