Save for Web: Transparency Dither makes a share of partly transparent pixels clear

With Transparency on, GIF and PNG-8 now offer Transparency Dither: No
Transparency Dither (the default, the half-opacity cut as before),
Diffusion with an Amount, Pattern and Noise. The help page describes the
four methods and the Diffusion amount:
https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400

- render: `clear_mask` decides which pixels take the transparent entry.
  Diffusion spreads the opacity error Floyd-Steinberg style over two rows,
  scaled by the amount; Pattern uses the 8x8 ordered matrix and Noise a
  fixed coordinate hash, so the same art always gives the same file. Fully
  clear and fully opaque pixels do not change. `quantize_locked`,
  `quantize_to`, `nearest_entries` and the fixed-palette path use it.
- engine: `document.exportForWeb`, its preview, `webExport.settings` and
  presets take `transparencyDither` (none, diffusion, pattern, noise) and
  `transparencyDitherAmount` (0 to 100, default 100). An unknown method or
  an amount over 100 is refused; settings saved without the keys take the
  defaults.
- ui: the Transparency Dither row sits under Transparency, with an Amount
  slider for Diffusion; both are disabled while Transparency is off and
  keep their values. Rows for the five labels are in every complete
  catalog.

The matrix, the noise, the amount mapping and the defaults' combination
with the matte are VectorCraft's own rules.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-20 22:15:41 -08:00
1 parent 9fff48d88f
commit b2e390f18f
39 files changed
+522 -36

No files matched your search

+9 -2
View File
@@ -701,8 +701,15 @@ impl Indexing {
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
}
};
let options =
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
let options = |r: Reduction| PaletteOptions {
colors: colors.unwrap_or(256),
reduction: r,
dither,
dither_amount,
transparency: true,
matte: None,
..PaletteOptions::default()
};
let refuse_colors = |name: &str| match colors {
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
None => Ok(()),
+1
View File
@@ -348,6 +348,7 @@ impl RasterOptions {
Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?,
None => Some([255; 3]),
},
..PaletteOptions::default()
},
tiff: TiffOptions {
color_model,
+17 -3
View File
@@ -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, 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",
"{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), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), 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
),
@@ -398,6 +398,12 @@ pub struct WebSettings {
pub dither_amount: u8,
/// Keep transparent pixels transparent (GIF, PNG-8, PNG-24).
pub transparency: bool,
/// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the
/// transparent entry and their color (`none`: under half opacity is transparent).
#[serde(serialize_with = "ser_key", deserialize_with = "de_key")]
pub transparency_dither: Dither,
/// 0–100: the strength of the `diffusion` transparency dither.
pub transparency_dither_amount: u8,
/// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`,
/// `black`, `none` or `#rrggbb`.
pub matte: String,
@@ -444,6 +450,8 @@ impl Default for WebSettings {
dither: Dither::Diffusion,
dither_amount: 100,
transparency: true,
transparency_dither: Dither::None,
transparency_dither_amount: 100,
matte: "white".into(),
interlaced: false,
web_snap: 0,
@@ -492,6 +500,10 @@ impl WebSettings {
fn checked(mut self) -> std::result::Result<Self, String> {
self.colors = self.colors.clamp(2, 256);
self.dither_amount = self.dither_amount.min(100);
if self.transparency_dither_amount > 100 {
let key = "transparencyDitherAmount";
return Err(format!("`{key}` must be from 0 to 100"));
}
self.web_snap = self.web_snap.min(100);
self.lossy = self.lossy.min(100);
self.quality = self.quality.min(100);
@@ -799,6 +811,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
dither_amount: s.dither_amount,
transparency: s.transparency,
matte,
transparency_dither: s.transparency_dither,
transparency_dither_amount: s.transparency_dither_amount,
};
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
// Map to transparent works on the colours the reduction made.
@@ -889,7 +903,7 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
return Ok(quantize::quantize_to(rgba, w, h, o, &left));
}
// A fixed palette holds at most `colors` entries, the transparent one included.
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
let has_clear = quantize::clear_mask(rgba, w, o).contains(&true);
let removed = custom.iter().any(|c| deleted.contains(c));
let mut left: Vec<[u8; 3]> = vec![];
for c in custom {
@@ -941,7 +955,7 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8;
return;
}
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
let near = quantize::nearest_entries(rgba, o, &all);
let near = quantize::nearest_entries(rgba, ix.width, o, &all);
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
return;
}
+86
View File
@@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() {
assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}");
}
/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them.
fn see_through() -> Session {
let mut s = session(40.0, 30.0);
rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000");
run(&mut s, "transparency.set", json!({"opacity": 25}));
rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff");
run(&mut s, "transparency.set", json!({"opacity": 75}));
s
}
/// The shares of the left and right halves' pixels that are opaque.
fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] {
[0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0)
}
#[test]
fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() {
let mut s = see_through();
for format in ["gif", "png8"] {
let file = |s: &mut Session, extra: Value| {
let mut p = json!({"format": format, "antiAlias": "none"});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
one(s, p)
};
// By default the pixels under half opacity are transparent and the others opaque.
let none = file(&mut s, json!({}));
assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}");
assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}");
assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
for method in ["diffusion", "pattern", "noise"] {
let p = json!({"transparencyDither": method});
let dithered = file(&mut s, p.clone());
let [left, right] = opaque_halves(&pixels(&dithered));
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
if format == "gif" {
assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}");
}
assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file");
// The preview shows what Save writes.
let mut pv = json!({"format": format, "antiAlias": "none", "image": true});
pv["transparencyDither"] = json!(method);
let shown = run(&mut s, "document.exportForWeb.preview", pv);
assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}");
// Without transparency the dither does nothing.
let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false}));
assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}");
}
// A fixed palette keeps the transparent entry for the dithered pixels.
let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}}));
let [left, right] = opaque_halves(&pixels(&fixed));
assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}");
}
}
#[test]
fn transparency_dither_settings_are_checked_and_remembered() {
let mut s = see_through();
for bad in [
json!({"transparencyDither": "spray"}),
json!({"transparencyDither": 3}),
json!({"transparencyDitherAmount": 101}),
json!({"transparencyDitherAmount": -1}),
] {
assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}");
assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}");
}
let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string();
assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}");
assert_eq!(defaults()["transparencyDither"], "none");
assert_eq!(defaults()["transparencyDitherAmount"], 100);
// The remembered settings and a saved preset keep both.
let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40}));
assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40)));
let read = run(&mut s, "webExport.settings", json!({}));
assert_eq!(read["settings"], set["settings"]);
run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60}));
let list = run(&mut s, "webExport.presets.list", json!({}));
let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap();
assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60)));
let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"}));
assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60})));
// Settings saved before the keys existed take the defaults.
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap();
assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100));
}
#[test]
fn jpeg_size_grows_with_quality() {
let mut s = many_colours();
+92 -27
View File
@@ -1,8 +1,9 @@
//! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by
//! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then
//! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an
//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry;
//! the others are blended over the matte colour.
//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or
//! with a transparency dither a share of the partly transparent pixels that follows their
//! opacity; the others are blended over the matte color.
use std::collections::HashMap;
@@ -111,11 +112,18 @@ pub struct PaletteOptions {
pub dither: Dither,
/// Dither strength 0–100.
pub dither_amount: u8,
/// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque.
/// Pixels under half opacity become a transparent entry (see `transparency_dither`);
/// otherwise every pixel is opaque.
pub transparency: bool,
/// The colour partly transparent pixels are blended over. `None`: with transparency, they
/// keep their own colour (hard edges); without, white.
pub matte: Option<[u8; 3]>,
/// With `transparency`, how partly transparent pixels are split between the transparent entry
/// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity.
pub transparency_dither: Dither,
/// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the
/// pattern and noise methods do not use it.
pub transparency_dither_amount: u8,
}
impl Default for PaletteOptions {
@@ -127,6 +135,8 @@ impl Default for PaletteOptions {
dither_amount: 100,
transparency: true,
matte: Some([255; 3]),
transparency_dither: Dither::None,
transparency_dither_amount: 100,
}
}
}
@@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind
/// them all anyway; locked colours no pixel ends up using are left out.
pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed {
let px = rgba.as_chunks::<4>().0;
let clear = |p: &[u8; 4]| o.transparency && p[3] < 128;
let clear = clear_mask(rgba, width, o);
let matte = o.matte.unwrap_or([255; 3]);
let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite));
let has_clear = px.iter().any(clear);
let has_clear = clear.contains(&true);
let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1);
let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c);
let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c);
// Locked colours take their slots first (at least one is left for the reduction).
let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k));
for c in locked {
@@ -185,7 +195,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
if palette.is_empty() {
palette.push(matte);
}
finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither })
finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither })
}
/// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither,
@@ -195,27 +205,82 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed {
let px = rgba.as_chunks::<4>().0;
let colors = opaque_colors(px, o, false);
let has_clear = o.transparency && px.iter().any(|p| p[3] < 128);
let clear = clear_mask(rgba, width, o);
let has_clear = clear.contains(&true);
let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect();
if palette.is_empty() {
palette.push(o.matte.unwrap_or([255; 3]));
}
finish(px, &colors, width, height, &palette, o, o.dither)
finish(&clear, &colors, width, height, &palette, o, o.dither)
}
/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures
/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a
/// pixel that becomes transparent, and for every pixel when `palette` is empty.
pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as
/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights)
/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every
/// pixel when `palette` is empty.
pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
let px = rgba.as_chunks::<4>().0;
let colors = opaque_colors(px, o, false);
let clear = clear_mask(rgba, width, o);
let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect();
let index = PaletteIndex::new(&pal, o.reduction.weights());
colors
.iter()
.zip(px)
.map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) })
.collect()
colors.iter().zip(&clear).map(|(c, &clear)| if pal.is_empty() || clear { None } else { Some(index.nearest(c.map(f32::from))) }).collect()
}
/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without
/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a
/// partly transparent pixel does under half opacity with no transparency dither, and else by
/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an
/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward
/// the cut at half opacity. Diffusion spreads each pixel's opacity error to the pixels right of it
/// and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), pattern compares the
/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only
/// on the pixels and the options, so exports are reproducible.
pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec<bool> {
let px = rgba.as_chunks::<4>().0;
if !o.transparency {
return vec![false; px.len()];
}
let width = (width as usize).min(px.len()).max(1);
let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0;
let dither = match o.transparency_dither {
Dither::Diffusion if amount == 0.0 => Dither::None,
d => d,
};
// Two rows of opacity error for diffusion (the current one and the next), one pixel of margin
// on each side.
let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }];
let half = err.len() / 2;
let mut out = Vec::with_capacity(px.len());
for (y, row) in px.chunks(width).enumerate() {
let (cur, next) = err.split_at_mut(half);
next.fill(0.0);
for (x, p) in row.iter().enumerate() {
let a = f32::from(p[3]);
let clear = match (p[3], dither) {
(0, _) => true,
(255, _) => false,
(_, Dither::None) => p[3] < 128,
(_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8),
// Another noise than the color dither's, so the two do not line up.
(_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5),
(_, Dither::Diffusion) => {
let v = a + cur[x + 1];
let clear = v < 127.5;
let e = (v - if clear { 0.0 } else { 255.0 }) * amount;
// 7/16 right, 3/16 below left, 5/16 below, 1/16 below right.
cur[x + 2] += e * 7.0 / 16.0;
next[x] += e * 3.0 / 16.0;
next[x + 1] += e * 5.0 / 16.0;
next[x + 2] += e / 16.0;
clear
}
};
out.push(clear);
}
cur.copy_from_slice(next);
}
out
}
/// The color of each pixel when opaque: blended over the matte, and gray when `gray`.
@@ -231,20 +296,20 @@ fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]>
.collect()
}
/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries
/// no pixel uses and put the transparent entry first when a pixel is transparent.
fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed {
let clear = |p: &[u8; 4]| o.transparency && p[3] < 128;
/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with
/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel
/// is transparent.
fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed {
let clear = |i: usize| clear.get(i).copied().unwrap_or(false);
let matte = o.matte.unwrap_or([255; 3]);
let has_clear = px.iter().any(clear);
let has_clear = (0..colors.len()).any(clear);
let weights = o.reduction.weights();
// (A width past the pixels there are would size the error rows from a number nothing checked.)
let mut indices =
map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i]));
let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear);
// Drop the entries no pixel uses (fixed palettes), keeping the order.
let mut used = [false; 256];
for (i, &ix) in indices.iter().enumerate() {
if !clear(&px[i]) {
if !clear(i) {
used[ix as usize] = true;
}
}
@@ -260,7 +325,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette:
}
}
for (i, ix) in indices.iter_mut().enumerate() {
*ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] };
*ix = if clear(i) { 0 } else { remap[*ix as usize] };
}
Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices }
}
+77 -1
View File
@@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node};
use vectorcraft_geom::shapes;
use super::png::{PngOptions, encode_indexed};
use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to};
use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to};
use super::*;
/// A `w`×`h` opaque image of `f(x, y)` colours.
@@ -252,3 +252,79 @@ fn ids_round_trip() {
assert_eq!(Dither::from_id(d.id()), Some(d));
}
}
/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`.
fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec<u8> {
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect()
}
/// The share of the pixels of `ix` that are not transparent.
fn opaque_share(ix: &Indexed) -> f64 {
ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64
}
fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions {
PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() }
}
#[test]
fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() {
let (w, h) = (32, 32);
for alpha in [64u8, 128, 191] {
let px = see_through(w, h, |_, _| alpha);
// No transparency dither cuts at half opacity, and so does Diffusion at 0.
let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100));
assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}");
assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}");
for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] {
let ix = quantize(&px, w, h, &alpha_dither(d, 100));
let share = opaque_share(&ix);
assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}");
assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}");
// The same pixels and options give the same image.
assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}");
// A fixed palette and the nearest entries make the same pixels transparent.
let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]);
assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette");
let near = nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]]);
let mask = clear_mask(&px, w, &alpha_dither(d, 100));
assert_eq!(near.iter().map(Option::is_none).collect::<Vec<_>>(), mask, "{d:?} at {alpha}");
}
// Diffusion at half strength keeps fewer pixels of a light area opaque than at full.
if alpha < 128 {
let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50)));
let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100)));
assert!(0.0 < half && half < full, "{alpha}: {half} {full}");
}
}
// The methods arrange the pixels differently.
let px = see_through(w, h, |_, _| 96);
let masks: Vec<Vec<bool>> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into();
assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]);
}
#[test]
fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() {
let (w, h) = (16, 8);
// Fully transparent on the left, opaque on the right: every method keeps them as they are.
let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 });
let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100));
assert_eq!(none.iter().filter(|c| **c).count(), 64);
for d in Dither::ALL {
assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}");
}
// Without transparency nothing is transparent, whatever the transparency dither.
let soft = see_through(w, h, |x, _| (x * 16) as u8);
for d in Dither::ALL {
let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) };
assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}");
assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}");
}
// A palette of two entries keeps one for the transparent pixels and one for the others.
let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) };
let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o);
assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0)));
// No pixels, and a width past the pixels there are.
assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty());
assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3);
}
+21 -1
View File
@@ -1,7 +1,7 @@
//! File → Export → Save for Web (Legacy) (`saveForWeb`, Ctrl/Cmd+Alt+Shift+S): the art previewed
//! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views,
//! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8,
//! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap,
//! PNG-24), color reduction, colors, dither, transparency and its dither, matte, interlacing, web snap,
//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color,
//! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker,
//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata,
@@ -823,6 +823,7 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
slider_row(ui, d, "ditherAmount", tl!("Amount:"), "%");
}
check_pair(ui, d, ("transparency", tl!("Transparency")), ("interlaced", tl!("Interlaced")));
transparency_dither_rows(ui, d);
matte_row(ui, d);
slider_row(ui, d, "webSnap", tl!("Web Snap:"), "%");
if format == WebFormat::Gif {
@@ -1083,6 +1084,25 @@ fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, suffix:
});
}
/// The Transparency Dither choices of GIF and PNG-8, as (`transparencyDither` value, label).
pub(crate) const TRANSPARENCY_DITHERS: [(&str, &str); 4] = [
("none", "No Transparency Dither"),
("diffusion", "Diffusion Transparency Dither"),
("pattern", "Pattern Transparency Dither"),
("noise", "Noise Transparency Dither"),
];
/// Transparency Dither and, for Diffusion, its Amount; both are disabled while Transparency is off
/// and keep their values.
fn transparency_dither_rows(ui: &mut egui::Ui, d: &mut Dialog) {
ui.add_enabled_ui(d.bool("transparency"), |ui| {
form::choice(ui, d, "transparencyDither", &crate::i18n::colon(tl!("Transparency Dither")), (LABEL_W, FIELD_W), &TRANSPARENCY_DITHERS);
if Dither::from_id(&d.str("transparencyDither")) == Some(Dither::Diffusion) {
slider_row(ui, d, "transparencyDitherAmount", tl!("Amount:"), "%");
}
});
}
/// The palette size: the usual counts, or any 2–256.
fn colors_row(ui: &mut egui::Ui, d: &mut Dialog) {
widgets::label_row(ui, tl!("Colors:"), LABEL_W, |ui| {
@@ -255,6 +255,61 @@ fn every_view_and_format_draws() {
assert_eq!(kind(&app), Some(save_for_web::KIND));
}
/// GIF and PNG-8 show Transparency Dither under Transparency, with an Amount slider for Diffusion;
/// both are disabled while Transparency is off and keep their values, PNG-24 does not show them, and
/// Done remembers them.
#[test]
fn transparency_dither_rows_follow_transparency_and_the_method() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, NodeT, Queryable};
type H<'a> = egui_kittest::Harness<'a, VectorcraftApp>;
let dir = vectorcraft_testkit::temp_dir("sfw-transparency-dither");
let (mut app, _) = app(&dir, false);
app.run("file.saveForWeb", json!({})).unwrap();
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 1200.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::theme::install_fonts(ui.ctx());
return;
}
show(app, ui.ctx());
},
app,
);
h.run_steps(4);
let disabled = |h: &H, value: &'static str| h.query(By::new().role(Role::ComboBox).value(value)).map(|n| n.accesskit_node().is_disabled());
let sliders = |h: &H| h.query_all(By::new().role(Role::Slider)).count();
let field = |h: &H, key: &str| h.state().ui.dialog.as_ref().unwrap().fields[key].clone();
assert_eq!(disabled(&h, "No Transparency Dither"), Some(false));
let before = sliders(&h);
h.get(By::new().role(Role::ComboBox).value("No Transparency Dither")).click();
h.run();
h.get_by_label("Diffusion Transparency Dither").click();
h.run();
assert_eq!(field(&h, "transparencyDither"), json!("diffusion"));
assert_eq!(sliders(&h), before + 1, "Diffusion has an Amount");
// Transparency off: the rows are disabled and keep their values.
set(h.state_mut(), "transparency", json!(false));
h.run();
assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(true));
assert_eq!(field(&h, "transparencyDither"), json!("diffusion"));
// PNG-24 has no transparency dither; PNG-8 has it again.
set(h.state_mut(), "format", json!("png24"));
h.run();
assert_eq!(disabled(&h, "Diffusion Transparency Dither"), None);
set(h.state_mut(), "format", json!("png8"));
set(h.state_mut(), "transparency", json!(true));
set(h.state_mut(), "transparencyDitherAmount", json!(35));
h.run();
assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(false));
// Done remembers them.
set(h.state_mut(), "discard", json!(true));
confirm(h.state_mut()).unwrap();
let s = h.state().session.last_web_settings();
assert_eq!((s.transparency_dither, s.transparency_dither_amount), (vectorcraft_render::encode::quantize::Dither::Diffusion, 35));
}
#[test]
fn save_remembers_and_writes_and_done_only_remembers() {
let dir = vectorcraft_testkit::temp_dir("sfw-save");
+5
View File
@@ -919,6 +919,11 @@ font-technology Variable Променливи
Distribute Spacing Разпределение на разстоянията
Distribute Spacing: Разпределение на разстоянията:
Dither: Дитъринг:
Transparency Dither Дитъринг на прозрачността
No Transparency Dither Без дитъринг на прозрачността
Diffusion Transparency Dither Дифузен дитъринг на прозрачността
Pattern Transparency Dither Дитъринг на прозрачността с мостра
Noise Transparency Dither Шумов дитъринг на прозрачността
Divide Разделяне
Divide Horizontally Into Разделяне хоризонтално на
Divide Objects Below Разделяне на обектите отдолу
Can't render this file because it is too large.
+5
View File
@@ -3174,6 +3174,11 @@ antiAlias Sharp Oštro
Convert to sRGB Pretvori u sRGB
Delete this saved preset Izbriši ovaj sačuvani predložak
Dither: Dithering:
Transparency Dither Dithering prozirnosti
No Transparency Dither Bez ditheringa prozirnosti
Diffusion Transparency Dither Difuzijski dithering prozirnosti
Pattern Transparency Dither Dithering prozirnosti uzorkom
Noise Transparency Dither Dithering prozirnosti šumom
Fit in View Uklopi u prikaz
Format: Format:
WebP WebP
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1360,6 +1360,11 @@ arrowhead Target Diana
Distribute Spacing: Distribueix l’espaiat:
Dither Tramatge
Dither: Tramatge:
Transparency Dither Tramatge de transparència
No Transparency Dither Sense tramatge de transparència
Diffusion Transparency Dither Tramatge de transparència per difusió
Pattern Transparency Dither Tramatge de transparència per motiu
Noise Transparency Dither Tramatge de transparència per soroll
Divide Divideix
Divide and Outline Will Remove Unpainted Artwork Divideix i contorneja eliminarà l’art no pintat
Divide Horizontally Into Divideix horitzontalment en
Can't render this file because it is too large.
+5
View File
@@ -3257,6 +3257,11 @@ antiAlias Sharp Ostré
Convert to sRGB Převést na sRGB
Delete this saved preset Odstranit toto uložené přednastavení
Dither: Rozptýlení:
Transparency Dither Rozptýlení průhlednosti
No Transparency Dither Bez rozptylu průhlednosti
Diffusion Transparency Dither Difuzní rozptýlení průhlednosti
Pattern Transparency Dither Rozptýlení průhlednosti vzorkem
Noise Transparency Dither Rozptýlení průhlednosti šumem
Fit in View Přizpůsobit zobrazení
Format: Formát:
WebP WebP
Can't render this file because it is too large.
+5
View File
@@ -5786,6 +5786,11 @@ antiAlias Sharp Skarp
Convert to sRGB Konvertér til sRGB
Delete this saved preset Slet denne gemte forudindstilling
Dither: Dither:
Transparency Dither Gennemsigtighedsdithering
No Transparency Dither Ingen gennemsigtighedsdithering
Diffusion Transparency Dither Diffusionsdithering af gennemsigtighed
Pattern Transparency Dither Mønsterdithering af gennemsigtighed
Noise Transparency Dither Støjdithering af gennemsigtighed
Fit in View Tilpas i visning
Format: Format:
WebP WebP
Can't render this file because it is too large.
+5
View File
@@ -940,6 +940,11 @@ font-technology Variable Variabel
Distribute Spacing Abstand verteilen
Distribute Spacing: Abstand verteilen:
Dither: Dithering:
Transparency Dither Transparenz-Dithering
No Transparency Dither Kein Transparenz-Dithering
Diffusion Transparency Dither Diffusion-Transparenz-Dithering
Pattern Transparency Dither Muster-Transparenz-Dithering
Noise Transparency Dither Rauschen-Transparenz-Dithering
Divide Fläche aufteilen
Divide Horizontally Into Horizontal teilen in
Divide Objects Below Darunterliegende Objekte aufteilen
Can't render this file because it is too large.
+5
View File
@@ -903,6 +903,11 @@ font-technology Variable Μεταβλητές
Distribute Spacing Κατανομή αποστάσεων
Distribute Spacing: Κατανομή αποστάσεων:
Dither: Πρόσθεση θορύβου:
Transparency Dither Πρόσμειξη θορύβου διαφάνειας
No Transparency Dither Χωρίς πρόσμειξη θορύβου διαφάνειας
Diffusion Transparency Dither Πρόσμειξη θορύβου διαφάνειας με διάχυση
Pattern Transparency Dither Πρόσμειξη θορύβου διαφάνειας με μοτίβο
Noise Transparency Dither Πρόσμειξη θορύβου διαφάνειας με θόρυβο
Divide Διαίρεση
Divide Horizontally Into Οριζόντια διαίρεση σε
Divide Objects Below Διαίρεση αντικειμένων από κάτω
Can't render this file because it is too large.
+5
View File
@@ -950,6 +950,11 @@ font-technology Variable Variables
Distribute Spacing Distribuir espaciado
Distribute Spacing: Distribuir espaciado:
Dither: Tramado:
Transparency Dither Tramado de transparencia
No Transparency Dither Sin tramado de transparencia
Diffusion Transparency Dither Tramado de transparencia por difusión
Pattern Transparency Dither Tramado de transparencia por motivo
Noise Transparency Dither Tramado de transparencia por ruido
Divide Dividir
Divide Horizontally Into Dividir horizontalmente en
Divide Objects Below Dividir objetos inferiores
Can't render this file because it is too large.
+5
View File
@@ -3199,6 +3199,11 @@ antiAlias Sharp Terävä
Convert to sRGB Muunna sRGB:ksi
Delete this saved preset Poista tämä tallennettu esiasetus
Dither: Rasterointi:
Transparency Dither Läpinäkyvyyden rasterointi
No Transparency Dither Ei läpinäkyvyyden rasterointia
Diffusion Transparency Dither Läpinäkyvyyden diffuusiorasterointi
Pattern Transparency Dither Läpinäkyvyyden kuviorasterointi
Noise Transparency Dither Läpinäkyvyyden kohinarasterointi
Fit in View Sovita näkymään
Format: Muoto:
WebP WebP
Can't render this file because it is too large.
+5
View File
@@ -953,6 +953,11 @@ font-technology Variable Variables
Distribute Spacing Répartir l’espacement
Distribute Spacing: Répartition de l’espacement :
Dither: Simulation :
Transparency Dither Simulation de transparence
No Transparency Dither Sans simulation de transparence
Diffusion Transparency Dither Simulation de transparence par diffusion
Pattern Transparency Dither Simulation de transparence par motif
Noise Transparency Dither Simulation de transparence par bruit
Divide Division
Divide Horizontally Into Diviser horizontalement en
Divide Objects Below Diviser les objets inférieurs
Can't render this file because it is too large.
+5
View File
@@ -1101,6 +1101,11 @@
Distribute Spacing: અંતર વિતરિત કરો:
Dither ડિથર
Dither: ડિથર:
Transparency Dither પારદર્શિતા ડિથર
No Transparency Dither પારદર્શિતા ડિથર નહીં
Diffusion Transparency Dither ડિફ્યુઝન પારદર્શિતા ડિથર
Pattern Transparency Dither પેટર્ન પારદર્શિતા ડિથર
Noise Transparency Dither નોઇઝ પારદર્શિતા ડિથર
Divide વિભાજિત કરો
Divide Horizontally Into આડી રીતે આમાં વિભાજિત કરો
Divide Objects Below નીચેના ઑબ્જેક્ટ્સ વિભાજિત કરો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+5
View File
@@ -1776,6 +1776,11 @@ arrowhead Feather पंख
Distribute Spacing: स्पेसिंग वितरित करें:
Dither डिथर
Dither: डिथर:
Transparency Dither पारदर्शिता डिथर
No Transparency Dither कोई पारदर्शिता डिथर नहीं
Diffusion Transparency Dither डिफ़्यूज़न पारदर्शिता डिथर
Pattern Transparency Dither पैटर्न पारदर्शिता डिथर
Noise Transparency Dither नॉइज़ पारदर्शिता डिथर
Divide विभाजित करें
Divide and Outline Will Remove Unpainted Artwork डिवाइड और आउटलाइन अनपेंटेड आर्टवर्क को हटा देगा
Divide Horizontally Into क्षैतिज रूप से विभाजित करें
Can't render this file because it is too large.
+5
View File
@@ -1222,6 +1222,11 @@ arrowhead Target Céltábla
Distribute Spacing Térköz elosztása
Distribute Spacing: Térköz elosztása:
Dither: Árnyalatkeverés:
Transparency Dither Átlátszóság-árnyalatkeverés
No Transparency Dither Nincs átlátszóság-árnyalatkeverés
Diffusion Transparency Dither Diffúziós átlátszóság-árnyalatkeverés
Pattern Transparency Dither Mintázatos átlátszóság-árnyalatkeverés
Noise Transparency Dither Zajos átlátszóság-árnyalatkeverés
Divide Felosztás
Divide Horizontally Into Vízszintes felosztás
Divide Objects Below Alatta lévő objektumok felosztása
Can't render this file because it is too large.
+5
View File
@@ -3658,6 +3658,11 @@ antiAlias Sharp Tajam
Convert to sRGB Konversi ke sRGB
Delete this saved preset Hapus preset tersimpan ini
Dither: Dither:
Transparency Dither Dither transparansi
No Transparency Dither Tanpa dither transparansi
Diffusion Transparency Dither Dither transparansi difusi
Pattern Transparency Dither Dither transparansi pola
Noise Transparency Dither Dither transparansi derau
Fit in View Sesuaikan ke tampilan
Format: Format:
WebP WebP
Can't render this file because it is too large.
+5
View File
@@ -961,6 +961,11 @@ font-technology Variable Variabili
Distribute Spacing Distribuisci spaziatura
Distribute Spacing: Distribuisci spaziatura:
Dither: Dithering:
Transparency Dither Dithering trasparenza
No Transparency Dither Nessun dithering trasparenza
Diffusion Transparency Dither Dithering trasparenza a diffusione
Pattern Transparency Dither Dithering trasparenza a motivo
Noise Transparency Dither Dithering trasparenza a disturbo
Divide Dividi
Divide Horizontally Into Dividi orizzontalmente in
Divide Objects Below Dividi oggetti sottostanti
Can't render this file because it is too large.
+5
View File
@@ -1722,6 +1722,11 @@ antiAlias Sharp シャープ
Distribute Spacing 等間隔に分布
Distribute Spacing: 間隔の分布:
Dither: ディザ:
Transparency Dither 透明部分のディザ
No Transparency Dither 透明部分のディザなし
Diffusion Transparency Dither 拡散の透明部分のディザ
Pattern Transparency Dither パターンの透明部分のディザ
Noise Transparency Dither ノイズの透明部分のディザ
Divide Horizontally Into 水平方向に分割
Divide Slices スライスを分割
Divide Vertically Into 垂直方向に分割
Can't render this file because it is too large.
+5
View File
@@ -5137,6 +5137,11 @@ antiAlias Sharp მკვეთრი
Convert to sRGB sRGB-ად გარდაქმნა
Delete this saved preset ამ შენახული პრესეტის წაშლა
Dither: დიზერინგი:
Transparency Dither გამჭვირვალობის დიზერინგი
No Transparency Dither გამჭვირვალობის დიზერინგის გარეშე
Diffusion Transparency Dither გამჭვირვალობის დიფუზიური დიზერინგი
Pattern Transparency Dither გამჭვირვალობის პატერნული დიზერინგი
Noise Transparency Dither გამჭვირვალობის ხმაურის დიზერინგი
Fit in View ხედში ჩატევა
Format: ფორმატი:
High მაღალი
Can't render this file because it is too large.
+5
View File
@@ -1712,6 +1712,11 @@ antiAlias Sharp 날카롭게
Distribute Spacing 간격 분포
Distribute Spacing: 간격 분포:
Dither: 디더:
Transparency Dither 투명도 디더
No Transparency Dither 투명도 디더 없음
Diffusion Transparency Dither 확산 투명도 디더
Pattern Transparency Dither 패턴 투명도 디더
Noise Transparency Dither 노이즈 투명도 디더
Divide Horizontally Into 가로로 나누기
Divide Slices 슬라이스 나누기
Divide Vertically Into 세로로 나누기
Can't render this file because it is too large.
+5
View File
@@ -3652,6 +3652,11 @@ antiAlias Sharp Scherp
Convert to sRGB Converteren naar sRGB
Delete this saved preset Deze opgeslagen voorinstelling verwijderen
Dither: Dither:
Transparency Dither Transparantiedithering
No Transparency Dither Geen transparantiedithering
Diffusion Transparency Dither Transparantiedithering met diffusie
Pattern Transparency Dither Transparantiedithering met patroon
Noise Transparency Dither Transparantiedithering met ruis
Fit in View In beeld passen
Format: Indeling:
WebP WebP
Can't render this file because it is too large.
+5
View File
@@ -3165,6 +3165,11 @@ antiAlias Sharp Ostre
Convert to sRGB Konwertuj na sRGB
Delete this saved preset Usuń to zapisane ustawienie
Dither: Rozpraszanie:
Transparency Dither Rozpraszanie przezroczystości
No Transparency Dither Bez rozpraszania przezroczystości
Diffusion Transparency Dither Dyfuzyjne rozpraszanie przezroczystości
Pattern Transparency Dither Rozpraszanie przezroczystości wzorkiem
Noise Transparency Dither Rozpraszanie przezroczystości szumem
Fit in View Dopasuj do widoku
Format: Format:
High Wysoka
Can't render this file because it is too large.
+5
View File
@@ -876,6 +876,11 @@ antiAlias Sharp Nítido
Distribute Spacing Distribuir Espaçamento
Distribute Spacing: Distribuir Espaçamento:
Dither: Dither:
Transparency Dither Dither de transparência
No Transparency Dither Sem dither de transparência
Diffusion Transparency Dither Dither de transparência por difusão
Pattern Transparency Dither Dither de transparência por padrão
Noise Transparency Dither Dither de transparência por ruído
Divide Dividir
Divide Horizontally Into Dividir Horizontalmente Em
Divide Objects Below Dividir Objetos Abaixo
Can't render this file because it is too large.
+5
View File
@@ -948,6 +948,11 @@ font-technology Variable Вариативные
Distribute Spacing Распределить интервалы
Distribute Spacing: Распределение интервалов:
Dither: Дизеринг:
Transparency Dither Дизеринг прозрачности
No Transparency Dither Без дизеринга прозрачности
Diffusion Transparency Dither Диффузный дизеринг прозрачности
Pattern Transparency Dither Дизеринг прозрачности узором
Noise Transparency Dither Шумовой дизеринг прозрачности
Divide Разделить
Divide Horizontally Into Разделить по горизонтали на
Divide Objects Below Разделить объекты ниже
Can't render this file because it is too large.
+5
View File
@@ -933,6 +933,11 @@ font-technology Variable Variabla
Distribute Spacing Fördela avstånd
Distribute Spacing: Fördela avstånd:
Dither: Dithering:
Transparency Dither Transparensdithering
No Transparency Dither Ingen transparensdithering
Diffusion Transparency Dither Transparensdithering med diffusion
Pattern Transparency Dither Transparensdithering med mönster
Noise Transparency Dither Transparensdithering med brus
Divide Dela upp
Divide Horizontally Into Dela horisontellt i
Divide Objects Below Dela objekt nedanför
Can't render this file because it is too large.
+12
View File
@@ -1128,6 +1128,18 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() {
}
}
/// Save for Web's Transparency Dither label and its choices (drawn translated by the dropdown, not
/// through `tl!`).
#[test]
fn transparency_dither_labels_are_in_complete_catalogs() {
for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) {
let cat = lang.catalog();
for label in std::iter::once("Transparency Dither").chain(crate::dialogs::save_for_web::TRANSPARENCY_DITHERS.map(|(_, l)| l)) {
assert!(cat.plain(label).is_some(), "{} is missing {label}", lang.code);
}
}
}
/// Each row in the `search` context, which adds a language's words to a group of words with the same
/// meaning for the command palette, names a group and adds single words of no other group, and no
/// two rows of a catalog add one word to different groups. No catalog has to have these rows.
+5
View File
@@ -929,6 +929,11 @@ font-technology Variable Değişken
Distribute Spacing Aralığı Dağıt
Distribute Spacing: Aralığı Dağıt:
Dither: Titreme:
Transparency Dither Saydamlık titremesi
No Transparency Dither Saydamlık titremesi yok
Diffusion Transparency Dither Difüzyon saydamlık titremesi
Pattern Transparency Dither Desen saydamlık titremesi
Noise Transparency Dither Gürültü saydamlık titremesi
Divide Böl
Divide Horizontally Into Yatay Olarak Böl
Divide Objects Below Aşağıdaki Nesneleri Böl
Can't render this file because it is too large.
+5
View File
@@ -955,6 +955,11 @@ font-technology Variable Варіативні
Distribute Spacing Розподілити інтервали
Distribute Spacing: Розподіл інтервалів:
Dither: Дизеринг:
Transparency Dither Дизеринг прозорості
No Transparency Dither Без дизерингу прозорості
Diffusion Transparency Dither Дифузійний дизеринг прозорості
Pattern Transparency Dither Дизеринг прозорості візерунком
Noise Transparency Dither Шумовий дизеринг прозорості
Divide Розділити
Divide Horizontally Into Розділити по горизонталі на
Divide Objects Below Розділити об’єкти нижче
Can't render this file because it is too large.
+5
View File
@@ -1122,6 +1122,11 @@ font-technology Variable Biến thiên
Distribute Spacing Phân bố khoảng cách
Distribute Spacing: Phân bố khoảng cách:
Dither: Dither:
Transparency Dither Dither độ trong suốt
No Transparency Dither Không dither độ trong suốt
Diffusion Transparency Dither Dither độ trong suốt khuếch tán
Pattern Transparency Dither Dither độ trong suốt họa tiết
Noise Transparency Dither Dither độ trong suốt nhiễu
Divide Chia
Divide Horizontally Into Chia ngang thành
Divide Objects Below Chia đối tượng bên dưới
Can't render this file because it is too large.
+5
View File
@@ -893,6 +893,11 @@ antiAlias Sharp 锐利
Distribute Spacing 按间距分布
Distribute Spacing: 分布间距:
Dither: 仿色:
Transparency Dither 透明度仿色
No Transparency Dither 无透明度仿色
Diffusion Transparency Dither 扩散透明度仿色
Pattern Transparency Dither 图案透明度仿色
Noise Transparency Dither 杂色透明度仿色
Divide 分割
Divide Horizontally Into 水平分割为
Divide Objects Below 分割下方对象
Can't render this file because it is too large.
+5
View File
@@ -923,6 +923,11 @@ font-technology Variable 可變
Distribute Spacing 均分間距
Distribute Spacing: 均分間距:
Dither: 仿色:
Transparency Dither 透明度仿色
No Transparency Dither 無透明度仿色
Diffusion Transparency Dither 擴散透明度仿色
Pattern Transparency Dither 圖樣透明度仿色
Noise Transparency Dither 雜訊透明度仿色
Divide 分割
Divide Horizontally Into 水平分割為
Divide Objects Below 分割下方物件
Can't render this file because it is too large.
+11 -2
View File
@@ -10531,8 +10531,8 @@ every option.
File → Export → Save for Web (Legacy) writes optimised web images: `document.exportForWeb {format: gif|jpg|png8|png24,
…}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at
`width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`,
`dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked,
transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24
`dither`, `ditherAmount`, `transparency`, `transparencyDither`, `transparencyDitherAmount`, `matte`, `interlaced`,
`webSnap`, `lossy` (GIF) and `colorTable {locked, transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24
`transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a
GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `<stem>` is the name of `path` without its extension, or
without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after
@@ -10543,6 +10543,15 @@ after a Windows device name such as `aux` (`slices: selected` writes the selecte
Without `path` the files come back as `{name, dataBase64}`. As in the raster exports, `warnings` says when an image
couldn't be decoded and is missing from the image; the files are written all the same.
With `transparency` on, `transparencyDither` sets how GIF and PNG-8 treat partly transparent pixels: `none` (the
default) makes the pixels under half opacity transparent and keeps the others; `diffusion`, `pattern` and `noise` make
some of them transparent and keep the rest in a diffusion pattern, an 8×8 ordered pattern or noise. With `pattern`,
`noise`, or `diffusion` at amount 100, about as many are kept as their opacity says. `transparencyDitherAmount` (0 to
100, default 100) sets the strength of `diffusion`: a lower amount comes closer to `none`, and 0 gives the same file as
`none`. Fully transparent and fully opaque pixels do not change, the same art and settings
always give the same file, and a kept pixel is blended over `matte` as before. Without `transparency` both keys are
kept and do not change the file. An unknown method or an amount outside 0 to 100 is refused.
`document.exportForWeb.preview` returns what Save writes for the same settings without writing it: `bytes` (the exact
file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table
(`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by
+1
View File
@@ -1003,6 +1003,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`).
- Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged.
- Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`).
- Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`).
- Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged.
- Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged.
- Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`).