mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 09:13:34 +00:00
Save for Web: GIF lossy moves no pixel into or out of a shifted color
Lossy compression compared each pixel with the reduction's colors, so a pixel next to a color shifted by hand could join that color and be written in its new color, and a pixel of the shifted color could leave it. Lossy now leaves the entries of shifted colors alone, as it does the transparent entry.
This commit is contained in:
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -814,10 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
*slot = *c;
|
||||
}
|
||||
}
|
||||
// Lossy compares the pixels with the colors the reduction made, so that a shifted color does
|
||||
// not take in the pixels of another color.
|
||||
// Lossy compares the pixels with the colors the reduction made, and moves no pixel into or out
|
||||
// of a color shifted by hand.
|
||||
if s.format == WebFormat::Gif {
|
||||
web::lossy(&mut ix, rgba, s.lossy);
|
||||
let fixed: Vec<u8> = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect();
|
||||
web::lossy(&mut ix, rgba, s.lossy, &fixed);
|
||||
}
|
||||
// The colors shifted by hand, then web shift and web snap (locked colors stay as they are).
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
|
||||
@@ -639,6 +639,23 @@ fn lossy_does_not_spread_a_shifted_color_into_another() {
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255]));
|
||||
}
|
||||
|
||||
/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to
|
||||
/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels.
|
||||
#[test]
|
||||
fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6");
|
||||
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
let near_blue = [20, 20, 230, 255];
|
||||
for x in 0..30 {
|
||||
let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue };
|
||||
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_and_remembered_settings() {
|
||||
let mut s = two_colours();
|
||||
|
||||
@@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() {
|
||||
let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]);
|
||||
let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() });
|
||||
let mut lossy_ix = ix.clone();
|
||||
lossy(&mut lossy_ix, &px, 80);
|
||||
lossy(&mut lossy_ix, &px, 80, &[]);
|
||||
let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
assert!(runs(&lossy_ix) < runs(&ix));
|
||||
let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len();
|
||||
assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix));
|
||||
let mut none = ix.clone();
|
||||
lossy(&mut none, &px, 0);
|
||||
lossy(&mut none, &px, 0, &[]);
|
||||
assert_eq!(none, ix);
|
||||
// A fixed entry keeps its pixels and takes no others.
|
||||
let fixed: Vec<u8> = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect();
|
||||
let mut kept = ix.clone();
|
||||
lossy(&mut kept, &px, 100, &fixed);
|
||||
assert_eq!(kept, ix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec<O
|
||||
|
||||
/// Lossy GIF compression: a pixel takes the entry of the pixel left of it when that entry is
|
||||
/// within `amount` (0–100) of its own colour in `rgba` (the straight pixels it was reduced from).
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8) {
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise. No pixel moves
|
||||
/// into or out of the transparent entry or an entry in `fixed`.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8, fixed: &[u8]) {
|
||||
let w = ix.width as usize;
|
||||
if amount == 0 || w == 0 || rgba.len() != ix.indices.len() * 4 {
|
||||
return;
|
||||
}
|
||||
// Up to 64 levels apart in each channel at 100.
|
||||
let limit = (f32::from(amount.min(100)) / 100.0 * 64.0).powi(2) * 3.0;
|
||||
let mut held = [false; 256];
|
||||
for i in fixed.iter().chain(&ix.transparent) {
|
||||
held[usize::from(*i)] = true;
|
||||
}
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) {
|
||||
for x in 1..row.len() {
|
||||
let (prev, cur) = (row[x - 1], row[x]);
|
||||
if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) {
|
||||
if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue };
|
||||
|
||||
+2
-1
@@ -9056,7 +9056,8 @@ locked one is: the shifted and locked colors take the palette's slots first, shi
|
||||
least one slot is left for the reduction, so with `colors: 2` and transparent pixels none is kept and a color left out
|
||||
shifts nothing. As with a locked color, a kept source stays in the palette when the art no longer has it, and the
|
||||
pixels nearest to it are written in the new color. The preview marks it `shifted` and `locked`. A shift by hand wins over `webShift`, `webSnap` and
|
||||
`locked`; a color mapped to transparent stays transparent. Two colors may be shifted to the same color. A source the
|
||||
`locked`; a color mapped to transparent stays transparent. GIF `lossy` moves no pixel into or out of a shifted color.
|
||||
Two colors may be shifted to the same color. A source the
|
||||
table does not hold shifts nothing, and the shift stays with the settings for when it comes back; another reduction
|
||||
keeps it. The settings store the map in lowercase, drop a color shifted to itself or deleted, and drop the `webShift`
|
||||
of a color shifted by hand. More than 256 entries, a key or value that is not a color such as `#ff8800` (`#rrggbbaa`
|
||||
|
||||
Reference in New Issue
Block a user