Files
vectorcraft/crates/doc/src/pixels.rs
T
bflatasticandClaude Opus 5.5 303689c8f4 M3.52: Eyedropper Options with Picks Up / Applies trees, Alt and Shift+Alt modes, image sampling
Double-clicking the Eyedropper opens Eyedropper Options (dialog
eyedropperOptions): raster sample size (point, 3x3, 5x5) and Picks Up /
Applies trees (transparency; focal fill colour, transparency, overprint;
focal stroke colour, transparency, overprint, weight, cap, join, miter,
dash; character and paragraph attributes). The options live in the
preferences (Prefs::eyedropper, eyedropper.setOptions, prefs key
eyedropper) and replace the earlier appearance/transparency switches.

appearance.copyFrom takes pickUp/apply overrides, reverse (Alt-click:
the selection's attributes onto the clicked object) and append
(Shift+Alt-click: add the source's fills and strokes). Type copies font,
size and paragraph attributes to type. Clicking an image samples its
pixels; sampled colours keep their colour model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:08:10 +07:00

131 lines
5.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Pixel access for embedded images: a stable content key and recolouring the pixels.
use std::collections::HashMap;
use std::io::Cursor;
use std::sync::Arc;
use crate::ImageBlob;
impl ImageBlob {
/// A PNG blob of `png` bytes.
pub fn png(png: Vec<u8>) -> Self {
Self { mime: "image/png".into(), bytes: Arc::new(png) }
}
/// A key derived from the bytes (FNV-1a), the same for identical images.
pub fn content_key(&self) -> String {
let h = self.bytes.iter().fold(0xcbf29ce484222325u64, |h, x| (h ^ *x as u64).wrapping_mul(0x100000001b3));
format!("img{h:016x}")
}
/// The image with `f` applied to each pixel's (straight) RGB, alpha kept and fully transparent
/// pixels left alone, re-encoded as PNG. `f` runs once per distinct colour. `None` when the
/// image can't be decoded or no pixel changed.
pub fn map_rgb(&self, mut f: impl FnMut([u8; 3]) -> [u8; 3]) -> Option<ImageBlob> {
let mut img = image::load_from_memory(&self.bytes).ok()?.to_rgba8();
let mut memo: HashMap<[u8; 3], [u8; 3]> = HashMap::new();
let mut changed = false;
for px in img.pixels_mut().filter(|p| p.0[3] > 0) {
let rgb = [px.0[0], px.0[1], px.0[2]];
let out = *memo.entry(rgb).or_insert_with(|| f(rgb));
if out != rgb {
px.0[..3].copy_from_slice(&out);
changed = true;
}
}
if !changed {
return None;
}
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(Self::png(png))
}
}
impl ImageBlob {
/// The colour around pixel (`x`, `y`) (pixel space): the alpha-weighted average of the `size` ×
/// `size` pixels centred on it, clipped to the image, as straight RGBA. `None` outside the
/// image, where every pixel is transparent, or when the image can't be decoded. The last image
/// decoded is kept for the next sample (the Eyedropper samples one image click after click).
pub fn sample(&self, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
thread_local! {
static LAST: std::cell::RefCell<Option<(String, Arc<image::RgbaImage>)>> = const { std::cell::RefCell::new(None) };
}
let key = self.content_key();
let img = LAST.with_borrow_mut(|last| match last {
Some((k, img)) if *k == key => Some(img.clone()),
_ => {
let img = Arc::new(image::load_from_memory(&self.bytes).ok()?.to_rgba8());
*last = Some((key, img.clone()));
Some(img)
}
})?;
let (w, h) = (img.width() as i64, img.height() as i64);
let (cx, cy) = (x.floor() as i64, y.floor() as i64);
if !(0..w).contains(&cx) || !(0..h).contains(&cy) {
return None;
}
let r = size.max(1) as i64 / 2;
let (mut sum, mut alpha, mut n) = ([0u64; 3], 0u64, 0u64);
for py in (cy - r).max(0)..=(cy + r).min(h - 1) {
for px in (cx - r).max(0)..=(cx + r).min(w - 1) {
let [pr, pg, pb, pa] = img.get_pixel(px as u32, py as u32).0;
let a = pa as u64;
sum = [sum[0] + pr as u64 * a, sum[1] + pg as u64 * a, sum[2] + pb as u64 * a];
alpha += a;
n += 1;
}
}
if alpha == 0 {
return None;
}
let c = |v: u64| ((v + alpha / 2) / alpha) as u8;
Some([c(sum[0]), c(sum[1]), c(sum[2]), ((alpha + n / 2) / n) as u8])
}
}
#[cfg(test)]
mod tests {
use super::*;
fn blob(px: &[[u8; 4]], w: u32, h: u32) -> ImageBlob {
let img = image::RgbaImage::from_raw(w, h, px.concat()).unwrap();
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
ImageBlob::png(png)
}
fn pixels(b: &ImageBlob) -> Vec<[u8; 4]> {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
#[test]
fn samples_a_pixel_or_the_average_around_it() {
let b = blob(&[[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [9, 9, 9, 0]], 4, 1);
assert_eq!(b.sample(1.5, 0.5, 1), Some([0, 255, 0, 255]));
assert_eq!(b.sample(1.5, 0.5, 3), Some([85, 85, 85, 255]), "red, green and blue averaged");
assert_eq!(b.sample(3.2, 0.5, 3), Some([0, 0, 255, 128]), "transparent pixels don't count towards the colour");
assert_eq!(b.sample(3.2, 0.5, 1), None, "all transparent");
assert_eq!(b.sample(-0.5, 0.5, 5), None, "outside");
assert_eq!(b.sample(0.0, 0.0, 5), Some([85, 85, 85, 255]), "clipped to the image");
}
#[test]
fn maps_each_colour_once_and_keeps_alpha() {
let b = blob(&[[255, 0, 0, 255], [255, 0, 0, 128], [0, 0, 255, 255], [10, 20, 30, 0]], 2, 2);
let mut calls = 0;
let out = b
.map_rgb(|[r, g, bl]| {
calls += 1;
[255 - r, 255 - g, 255 - bl]
})
.unwrap();
assert_eq!(calls, 2, "red and blue, once each; the transparent pixel is skipped");
assert_eq!(pixels(&out), [[0, 255, 255, 255], [0, 255, 255, 128], [255, 255, 0, 255], [10, 20, 30, 0]]);
assert_ne!(out.content_key(), b.content_key());
assert_eq!(b.content_key(), blob(&[[255, 0, 0, 255], [255, 0, 0, 128], [0, 0, 255, 255], [10, 20, 30, 0]], 2, 2).content_key());
assert!(b.map_rgb(|c| c).is_none(), "nothing changed");
assert!(ImageBlob::png(vec![1, 2, 3]).map_rgb(|c| c).is_none(), "undecodable");
}
}