WebP export: Embed ICC Profile writes the sRGB profile in an ICCP chunk

WebP had no embedIcc option, and its encoder never attached a profile,
so no WebP file carried one. WebP now takes embedIcc like JPEG, TIFF and
PSD, on by default: the file becomes an extended (VP8X) file holding the
sRGB profile in an ICCP chunk, lossless or lossy. embedIcc: false writes
the plain file as before.

- document.export and Export for Screens' settings.webp take embedIcc,
  and document.formats lists it for WebP.
- WebP Options (Export As and Export for Screens' Format Settings) gets
  an Embed ICC Profile checkbox.
- Docs: docs/mcp.md and docs/file-format-parity.md.
This commit is contained in:
dotCooCoo committed 2026-12-04 15:24:10 -08:00
1 parent 534291eb8f
commit 87778a672b
12 files changed
+113 -25

No files matched your search

+1 -1
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer f Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chos Line truncated
has_doc,
export::export
),
+1
View File
@@ -352,6 +352,7 @@ impl RasterOptions {
interlaced: self.interlaced.unwrap_or(false),
quality: self.quality()?.unwrap_or(90).min(100),
webp_lossless: self.lossless.unwrap_or(true),
webp_embed_icc: embed_icc,
jpeg: JpegOptions {
color_model,
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
+17 -2
View File
@@ -159,7 +159,7 @@ const EMBED_ICC: FormatOption = FormatOption {
name: "embedIcc",
ty: "boolean",
default: "true",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk); WebP: the sRGB profile in an ICCP chunk",
};
const IMAGE_MAP: FormatOption = FormatOption {
@@ -470,7 +470,22 @@ pub const FORMATS: &[Format] = &[
read: true,
write: true,
raster: true,
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY],
options: &[
ARTBOARD,
ARTBOARDS,
RANGE,
USE_ARTBOARDS,
RECT,
PPI,
SCALE,
WIDTH,
HEIGHT,
BACKGROUND,
ANTI_ALIAS,
LOSSLESS,
WEBP_QUALITY,
EMBED_ICC,
],
},
Format {
id: "tiff",
@@ -229,6 +229,31 @@ fn png_says_it_is_srgb_unless_embed_icc_is_false() {
assert!(f["options"].get("embedIcc").is_some(), "png lists embedIcc");
}
/// WebP, lossless or lossy, holds the sRGB profile in an `ICCP` chunk unless `embedIcc` is false,
/// in Export As and in Export for Screens' `settings.webp`, without a note on an unused option.
#[test]
fn webp_embeds_the_srgb_profile_unless_embed_icc_is_false() {
let mut s = session(40.0, 30.0, 1);
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
let has_iccp = |file: &[u8]| file.windows(4).any(|w| w == b"ICCP");
for lossless in [true, false] {
let on = s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap();
assert!(has_iccp(&b64(&on)), "lossless {lossless}");
let off = s.execute("document.export", &json!({"format": "webp", "lossless": lossless, "embedIcc": false})).unwrap();
assert!(!has_iccp(&b64(&off)), "lossless {lossless}");
assert_eq!(off["warnings"], json!([]), "lossless {lossless}: embedIcc is a WebP option");
}
let screens = |s: &mut Session, settings: Value| {
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp"}], "settings": settings})).unwrap();
b64(&r["files"][0])
};
assert!(has_iccp(&screens(&mut s, json!({}))));
assert!(!has_iccp(&screens(&mut s, json!({"webp": {"embedIcc": false}}))));
let r = s.execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "webp").unwrap();
assert!(f["options"].get("embedIcc").is_some(), "webp lists embedIcc");
}
#[test]
fn formats_list_the_raster_options() {
let mut s = Session::new();
+7 -6
View File
@@ -95,13 +95,13 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
(b64(&r), r["warnings"].clone())
};
let (lossless, warnings) = export(&mut s, json!({}));
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
assert_eq!(webp_chunks(&lossless), [*b"VP8X", *b"ICCP", *b"VP8L"], "lossless with the profile by default");
assert_eq!(warnings, json!([]));
// Quality doesn't change a lossless file.
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"VP8 "], "opaque art has no alpha chunk");
assert_eq!(warnings, json!([]), "no note: the file is lossy");
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
@@ -114,10 +114,11 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
// Lower quality, smaller file.
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
assert_eq!(webp_chunks(&low), [*b"VP8X", *b"ICCP", *b"VP8 "]);
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
for q in [0, 100] {
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
let file = export(&mut s, json!({"lossless": false, "quality": q, "embedIcc": false})).0;
assert_eq!(webp_chunks(&file), [*b"VP8 "], "quality {q}: a plain lossy file without the profile");
}
}
@@ -130,7 +131,7 @@ fn lossy_webp_keeps_translucent_pixels() {
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"ALPH", *b"VP8 "]);
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
assert_eq!((lw, lh), (w, h));
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
@@ -161,7 +162,7 @@ fn webp_quality_out_of_its_range_is_refused() {
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
let file = b64(&r["files"][0]);
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ICCP", *b"VP8 "]);
}
#[test]
+15 -4
View File
@@ -53,6 +53,8 @@ pub struct RasterExportOptions {
pub quality: u8,
/// WebP: lossless (`true`), or lossy at [`Self::quality`].
pub webp_lossless: bool,
/// WebP: the sRGB profile in an `ICCP` chunk.
pub webp_embed_icc: bool,
/// JPEG colour model, coding and profile.
pub jpeg: jpeg::JpegOptions,
/// PNG-8 and GIF: the colour reduction (also BMP's at 1, 4 and 8 bits).
@@ -79,6 +81,7 @@ impl Default for RasterExportOptions {
interlaced: false,
quality: 90,
webp_lossless: true,
webp_embed_icc: true,
jpeg: jpeg::JpegOptions::default(),
palette: quantize::PaletteOptions::default(),
tiff: tiff::TiffOptions::default(),
@@ -128,7 +131,7 @@ impl RasterExportOptions {
};
jpeg::encode(&px, img.width, img.height, self.quality, Some(self.ppi), &self.jpeg)
}
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality)),
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality), self.webp_embed_icc),
RasterFormat::Png8 | RasterFormat::Gif => {
let ix = quantize::quantize(&img.to_straight(), img.width, img.height, &self.palette);
match format {
@@ -188,8 +191,14 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] {
}
/// WebP: lossless (`VP8L`) when `lossy_quality` is `None`, else lossy (`VP8 `, with an `ALPH`
/// chunk when some pixels are not opaque) at that quality 0–100.
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>, String> {
/// chunk when some pixels are not opaque) at that quality 0–100. With `embed_icc` the file is
/// extended (`VP8X`) and holds the sRGB profile in an `ICCP` chunk.
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>, embed_icc: bool) -> Result<Vec<u8>, String> {
let icc = if embed_icc {
Some(vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).map_err(|e| format!("WebP colour profile: {e}"))?.to_vec())
} else {
None
};
let src = craft_image_codecs::Image::from_raw(
img.width,
img.height,
@@ -197,10 +206,12 @@ pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>,
craft_image_codecs::SampleType::U8,
img.to_straight(),
)
.map_err(|e| format!("WebP encoding failed: {e}"))?;
.map_err(|e| format!("WebP encoding failed: {e}"))?
.with_icc(icc);
let opts = craft_image_codecs::EncodeOptions {
webp_lossless: lossy_quality.is_none(),
webp_quality: lossy_quality.unwrap_or(100).min(100),
embed_icc,
..craft_image_codecs::EncodeOptions::default()
};
let file = craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))?;
+32 -2
View File
@@ -220,9 +220,10 @@ fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
#[test]
fn lossy_webp_keeps_transparent_pixels_transparent() {
let d = circle_doc();
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap();
let no_icc = RasterExportOptions { webp_embed_icc: false, ..Default::default() };
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &no_icc).unwrap();
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..Default::default() };
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..no_icc };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ALPH", *b"VP8 "]);
let img = export(&d, RasterFormat::WebP, &o);
@@ -236,6 +237,35 @@ fn lossy_webp_keeps_transparent_pixels_transparent() {
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
}
/// The payload of the first chunk of type `ty` in RIFF WebP `file`.
fn webp_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> &'a [u8] {
let at = chunk_offset(file, ty);
let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize;
&file[at + 8..at + 8 + len]
}
/// By default a WebP file, lossless or lossy, holds the sRGB profile in an `ICCP` chunk that its
/// `VP8X` header flags, and a decoder reads the profile back; with `webp_embed_icc` off it holds
/// none.
#[test]
fn webp_embeds_the_srgb_profile_unless_told_not_to() {
let d = circle_doc();
let srgb = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap();
for lossless in [true, false] {
let o = RasterExportOptions { webp_lossless: lossless, ..Default::default() };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
let chunks = webp_chunks(&file);
assert_eq!(chunks[..2], [*b"VP8X", *b"ICCP"], "lossless {lossless}: {chunks:?}");
assert_ne!(webp_chunk(&file, b"VP8X")[0] & 0x20, 0, "lossless {lossless}: the VP8X ICC flag");
assert_eq!(webp_chunk(&file, b"ICCP"), &*srgb, "lossless {lossless}");
let mut dec = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&file)).unwrap();
assert_eq!(image::ImageDecoder::icc_profile(&mut dec).unwrap().as_deref(), Some(&*srgb), "lossless {lossless}");
let off = RasterExportOptions { webp_embed_icc: false, ..o };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &off).unwrap();
assert!(!webp_chunks(&file).contains(b"ICCP"), "lossless {lossless}");
}
}
/// A lossy frame's tag (RFC 6386 §9.1) holds its first partition's size in 19 bits. A frame whose
/// size field is at that limit may hold a larger partition, so it is refused; frames below it
/// decode with another decoder at every quality, a 1 × 1 image and transparent pixels included.
+1 -1
View File
@@ -421,7 +421,7 @@ impl Rendered {
}
/// Encode as lossless WebP.
pub fn to_webp(&self) -> Result<Vec<u8>, String> {
encode::webp(self, None)
encode::webp(self, None, false)
}
/// Straight-alpha RGBA at (x, y).
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
+4 -3
View File
@@ -1,6 +1,6 @@
//! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced),
//! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image
//! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
//! map), WebP Options (lossless, or lossy at a quality 0–100, and the profile), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
//! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options
//! ([`super::psd_options`]). Fields
//! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the
@@ -115,7 +115,7 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map<String, Value> {
o.insert("interlaced".into(), json!(false));
}
"webp" => {
o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY))]);
o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY)), ("embedIcc".into(), json!(true))]);
}
"jpg" => {
let model = if cmyk { ColorModel::Cmyk } else { ColorModel::Rgb };
@@ -337,7 +337,7 @@ fn quality_row() -> Param {
}
/// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses
/// (disabled while Lossless is chosen, keeping its value).
/// (disabled while Lossless is chosen, keeping its value), and Embed ICC Profile (sRGB).
fn webp_rows() -> Vec<Param> {
let [lossless, lossy] = WEBP_COMPRESSION_LABELS;
let compression = ParamKind::radio(vec![("true".into(), tl!(lossless).into()), ("false".into(), tl!(lossy).into())], Some("true".into()));
@@ -345,6 +345,7 @@ fn webp_rows() -> Vec<Param> {
Param::new("lossless", tl!("Compression:"), compression),
Param::new("quality", tl!("Quality:"), ParamKind::range(0.0, 100.0, f64::from(WEBP_QUALITY), SliderScale::Linear))
.enabled_when("lossless", "false"),
check("embedIcc", tl!("Embed ICC Profile"), true),
]
}
@@ -45,8 +45,9 @@ fn raster_option_rows_reach_the_export_params() {
assert_eq!(gif[10] & 0x07, 1, "a global colour table of 4 entries");
}),
("png8", &[("reduction", json!("gray"))], |png| assert_eq!(png[25], 3, "indexed")),
("webp", &[("lossless", json!("false")), ("quality", json!(40))], |file| {
("webp", &[("lossless", json!("false")), ("quality", json!(40)), ("embedIcc", json!(false))], |file| {
assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy");
assert!(!file.windows(4).any(|w| w == b"ICCP"), "no profile");
}),
("tiff", &[("byteOrder", json!("big")), ("colorModel", json!("cmyk")), ("lzw", json!(false))], |tiff| assert_eq!(&tiff[..4], b"MM\0*")),
("tga", &[("depth", json!("32"))], |tga| assert_eq!((tga[16], tga[17]), (32, 8))),
@@ -165,7 +166,8 @@ fn text_export_options_write_the_stories() {
assert_eq!((path.as_str(), bytes.as_slice()), ("/out/Untitled-1.txt", &b"Hello\r\nthere\r\n"[..]));
}
/// WebP is lossless by default, and OK writes a lossless file without a note.
/// WebP is lossless with the sRGB profile by default, and OK writes a lossless file holding the
/// profile, without a note.
#[test]
fn webp_is_lossless_by_default() {
let (mut app, written) = app(1);
@@ -175,7 +177,9 @@ fn webp_is_lossless_by_default() {
frame(&mut app);
confirm(&mut app);
assert!(!app.ui.status.contains("note"), "{}", app.ui.status);
assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default");
let file = written.borrow()[0].1.clone();
assert!(file.windows(4).any(|w| w == b"VP8L"), "lossless by default");
assert!(file.windows(4).any(|w| w == b"ICCP"), "the profile by default");
}
#[test]
+1 -1
View File
@@ -378,7 +378,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | |
| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) |
| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` |
| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90; `embedIcc`, default on, writes the sRGB profile in an `ICCP` chunk) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` |
| JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` |
| HEIC / HEIF | open, place | yes (HEVC-coded still images: single pictures and grids of tiles, 8 to 10 bits, with an alpha image; image sequences, other codings and grids of cropped tiles are refused) | no | `.heic`, `.heif`; decoded by heic-rs in the engine's default `heif` feature (a build without it refuses the files with a message); the container's rotation, mirror and crop are applied; without an `nclx` box the HEVC stream's video signal type gives the matrix and range; an RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; EXIF resolution tags size the image, or 72 ppi; bounded decoding; `tests_heifread.rs` |
| Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` |
+2 -2
View File
@@ -1634,8 +1634,8 @@ their own size (`scale: "512w"`).
WebP is lossless by default (`lossless: true`). `{"format": "webp", "lossless": false, "quality": 60}` writes a lossy
WebP file: `quality` runs from 0 to 100 (default 90, VectorCraft's own value), and a higher value keeps more detail in
a larger file. A lossy file keeps the alpha exactly when some pixels are not opaque. A WebP `quality` above 100, or one
that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row
or in `settings.webp`.
that is not a whole number, is refused; a lossless file ignores `quality`. A WebP file holds the sRGB profile in an
`ICCP` chunk unless `embedIcc` is false. Export for Screens takes these options in a WebP row or in `settings.webp`.
GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`)
and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as