mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 06:38:44 +00:00
Save for Web: a fixed palette keeps an opaque color when it maps colors to transparent
With a fixed palette (Custom table), the colors listed in colorTable.transparent all become the one transparent entry, so together they now take a single slot of Colors, and the opaque colors fill the remaining slots in palette order. Before, the palette was cut to its first entries; when those were all mapped to transparent, every opaque pixel took one of them and the whole image turned transparent, and with a deleted color the export was refused although an opaque color was left past the cut. The check that a deletion leaves an opaque color now reads the whole palette. When no pixel is transparent and no pixel takes a color mapped to transparent, that slot goes to the next opaque color. At 256 colors one entry stays for a color mapped to transparent.
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; 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",
|
||||
"{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, its transparent colors taking one slot together; 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
|
||||
),
|
||||
@@ -866,7 +866,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
|
||||
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
|
||||
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
|
||||
/// transparent.
|
||||
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
|
||||
/// `colors` together, and its first opaque colors that fit in the rest.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
@@ -895,11 +896,37 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
|
||||
left.push(c);
|
||||
}
|
||||
}
|
||||
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
|
||||
if left.is_empty() || (removed && !opaque_left(&left)) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
Ok(quantize::quantize_to(rgba, w, h, o, &left))
|
||||
// The colors mapped to transparent all become the one transparent entry, so together they take
|
||||
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
|
||||
// them and no pixel is transparent, that slot goes to the next opaque color instead.
|
||||
let ix = quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, true));
|
||||
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
|
||||
}
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
|
||||
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
|
||||
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
|
||||
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
|
||||
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
|
||||
let total = 256 - usize::from(has_clear);
|
||||
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
|
||||
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
|
||||
let mut clear_room = if clear { total - opaque } else { 0 };
|
||||
left.iter()
|
||||
.copied()
|
||||
.filter(|c| {
|
||||
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
|
||||
let keep = *slots > 0;
|
||||
*slots = slots.saturating_sub(1);
|
||||
keep
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
|
||||
@@ -539,6 +539,55 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
|
||||
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
|
||||
}
|
||||
|
||||
/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the
|
||||
/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the
|
||||
/// pixels of the colors mapped to transparent become transparent.
|
||||
#[test]
|
||||
fn colour_table_fixed_palette_keeps_an_opaque_color() {
|
||||
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
|
||||
let mut s = session(40.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
for table in [
|
||||
json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}),
|
||||
json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}),
|
||||
] {
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table});
|
||||
let v = run(&mut s, "document.exportForWeb.preview", p.clone());
|
||||
let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect();
|
||||
assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}");
|
||||
let img = pixels(&one(&mut s, p.clone()));
|
||||
let alpha = |x: u32| img.get_pixel(x, 5).0[3];
|
||||
assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}");
|
||||
}
|
||||
// A color mapped to transparent that no pixel takes leaves its slot to an opaque color.
|
||||
let mut u = session(20.0, 10.0);
|
||||
rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut u, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255]));
|
||||
// At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry.
|
||||
let full: Vec<String> =
|
||||
std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0));
|
||||
// Without transparent pixels the colors mapped to transparent still take one slot together.
|
||||
let mut t = session(30.0, 10.0);
|
||||
rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {
|
||||
"customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"],
|
||||
}});
|
||||
let v = run(&mut t, "document.exportForWeb.preview", p.clone());
|
||||
assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}");
|
||||
let img = pixels(&one(&mut t, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
|
||||
}
|
||||
|
||||
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
|
||||
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
|
||||
/// the file.
|
||||
|
||||
+3
-1
@@ -9041,7 +9041,9 @@ file agree. A deleted color also leaves `locked`, `transparent` and `webShift`.
|
||||
ignored. Deleting every opaque color is an error, and the settings, preview and files do not change; the transparent
|
||||
entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom
|
||||
table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it
|
||||
lacks is not made again; the dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold
|
||||
lacks is not made again. Its colors in `transparent` all become the transparent entry and take one of the `colors`
|
||||
slots together (when no pixel is transparent and no pixel takes one of them, that slot goes to its next color); its
|
||||
other colors fill the remaining slots in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold
|
||||
at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears
|
||||
both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In
|
||||
the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and
|
||||
|
||||
Reference in New Issue
Block a user