mirror of
https://github.com/storytold/designcraft.git
synced 2026-12-02 20:21:15 -05:00
Keep white pixels transparent for uncoloured 1-bit bitmap rasters (#3379)
This commit is contained in:
1 parent
b505760b6e
commit
9869f0ff80
8 files changed
+337
-24
No files matched your search
@@ -16,7 +16,7 @@ mod tiff_reduced;
|
||||
mod tone;
|
||||
pub use craft_ps::read::is_eps;
|
||||
pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size};
|
||||
pub use tone::{Tone, tone};
|
||||
pub use tone::{Tone, is_bitmap, tone};
|
||||
|
||||
/// CSS pixels (SVG user units) → points.
|
||||
pub const PT_PER_PX: f64 = 0.75;
|
||||
|
||||
@@ -11,6 +11,15 @@ pub enum Tone {
|
||||
Bitmap,
|
||||
}
|
||||
|
||||
/// Whether `bytes` is a 1-bit (bitmap mode) raster: TIFF, PNG, PSD or BMP with one channel and
|
||||
/// one bit per sample. Header-only (never decodes pixels).
|
||||
pub fn is_bitmap(bytes: &[u8]) -> bool {
|
||||
craft_image_codecs::inspect_raster(bytes)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some_and(|info| info.channels == 1 && info.color_type == craft_image_codecs::RasterColorType::Bitmap)
|
||||
}
|
||||
|
||||
/// The [`Tone`] of an image file, `None` when a swatch doesn't colour it.
|
||||
pub fn tone(bytes: &[u8]) -> Option<Tone> {
|
||||
if let Some(info) = craft_image_codecs::inspect_raster(bytes).ok().flatten()
|
||||
@@ -79,17 +88,21 @@ mod tests {
|
||||
png
|
||||
}
|
||||
|
||||
/// A 1-bit TIFF (BlackIsZero), one row of 8 pixels, uncompressed.
|
||||
/// A 1-bit TIFF (`photometric`: 0 = WhiteIsZero, 1 = BlackIsZero), one row of 8 pixels, uncompressed.
|
||||
fn tiff_1bit(bits: u8) -> Vec<u8> {
|
||||
tiff_1bit_with(bits, 1)
|
||||
}
|
||||
|
||||
fn tiff_1bit_with(bits: u8, photometric: u32) -> Vec<u8> {
|
||||
let entries: [(u16, u16, u32); 8] = [
|
||||
(256, 3, 8), // width
|
||||
(257, 3, 1), // height
|
||||
(258, 3, 1), // bits per sample
|
||||
(259, 3, 1), // no compression
|
||||
(262, 3, 1), // BlackIsZero
|
||||
(273, 4, 8), // strip offset
|
||||
(278, 3, 1), // rows per strip
|
||||
(279, 4, 1), // strip byte count
|
||||
(256, 3, 8), // width
|
||||
(257, 3, 1), // height
|
||||
(258, 3, 1), // bits per sample
|
||||
(259, 3, 1), // no compression
|
||||
(262, 3, photometric), // PhotometricInterpretation
|
||||
(273, 4, 8), // strip offset
|
||||
(278, 3, 1), // rows per strip
|
||||
(279, 4, 1), // strip byte count
|
||||
];
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend(10u32.to_le_bytes());
|
||||
@@ -134,6 +147,7 @@ mod tests {
|
||||
assert_eq!(tone(&encode(&wide, 2, 2, ExtendedColorType::L16, Png)), Some(Tone::Gray));
|
||||
assert_eq!(tone(&png_1bit(8, 0b1010_0000)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&tiff_1bit(0b1100_0000)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&tiff_1bit_with(0b1100_0000, 0)), Some(Tone::Bitmap));
|
||||
assert_eq!(tone(&psd_header(1, 1)), Some(Tone::Gray));
|
||||
assert_eq!(tone(&psd_header(1, 0)), Some(Tone::Bitmap));
|
||||
|
||||
@@ -145,6 +159,25 @@ mod tests {
|
||||
assert_eq!(tone(&encode(&greys, 2, 2, ExtendedColorType::Rgba8, Gif)), Some(Tone::Gray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_bitmap_matches_one_bit_rasters_only() {
|
||||
use image::ImageFormat::{Gif, Jpeg, Png, Tiff};
|
||||
assert!(is_bitmap(&tiff_1bit_with(0b1010_0000, 0)));
|
||||
assert!(is_bitmap(&tiff_1bit_with(0b1010_0000, 1)));
|
||||
assert!(is_bitmap(&png_1bit(8, 0b1010_0000)));
|
||||
assert!(is_bitmap(&psd_header(1, 0)));
|
||||
|
||||
let grey = [0u8, 128, 255, 64];
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Tiff)));
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Png)));
|
||||
assert!(!is_bitmap(&encode(&grey, 2, 2, ExtendedColorType::L8, Jpeg)));
|
||||
assert!(!is_bitmap(&psd_header(1, 1)));
|
||||
assert!(!is_bitmap(&psd_header(2, 0)));
|
||||
let bw_gif = [[0u8, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255]].concat();
|
||||
assert!(!is_bitmap(&encode(&bw_gif, 2, 2, ExtendedColorType::Rgba8, Gif)));
|
||||
assert!(!is_bitmap(b""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_and_alpha_files_keep_their_colours() {
|
||||
use image::ImageFormat::{Gif, Png};
|
||||
|
||||
@@ -341,18 +341,31 @@ impl Exporter<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
/// A greyscale or bitmap image coloured by the swatch applied to it (#1094): the swatch is
|
||||
/// painted through the image's ink coverage (its darkness), over 0% ink for a greyscale
|
||||
/// image, whose white is opaque. `false`, drawing nothing, when the image keeps its own
|
||||
/// colours: no swatch, one that no longer exists, a colour image. With `compress_images` the
|
||||
/// coverage is a grey JPEG, as the image itself would be.
|
||||
/// A greyscale or bitmap image coloured by the swatch applied to it (#1094), or a 1-bit
|
||||
/// (bitmap mode) image with no swatch applied (default `[Black]`): the swatch is painted
|
||||
/// through the image's ink coverage (its darkness), over 0% ink for a greyscale image, whose
|
||||
/// white is opaque, and with transparent white for a bitmap image. `false`, drawing nothing,
|
||||
/// when the image keeps its own colours: a colour image, an uncoloured greyscale image, or
|
||||
/// one with a missing swatch. With `compress_images` the coverage is a grey JPEG for
|
||||
/// greyscale images, as the image itself would be.
|
||||
fn colorized(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic) -> bool {
|
||||
if g.fill.is_none() {
|
||||
return false;
|
||||
}
|
||||
let Some((bytes, _)) = self.asset_bytes(g.asset) else { return false };
|
||||
let Some(tone) = designcraft_images::tone(&bytes) else { return false };
|
||||
let Some(paint) = self.swatch_color(&g.fill.swatch, g.fill.tint) else { return false };
|
||||
let default_black =
|
||||
|| self.swatch_color(designcraft_color::swatch::BLACK, 1.0).unwrap_or_else(|| device(&Color::cmyk(0.0, 0.0, 0.0, 1.0), self.rgb_only));
|
||||
let (tone, paint) = if g.fill.is_none() {
|
||||
if !designcraft_images::is_bitmap(&bytes) {
|
||||
return false;
|
||||
}
|
||||
(designcraft_images::Tone::Bitmap, default_black())
|
||||
} else {
|
||||
let Some(tone) = designcraft_images::tone(&bytes) else { return false };
|
||||
let paint = match self.swatch_color(&g.fill.swatch, g.fill.tint) {
|
||||
Some(paint) => paint,
|
||||
None if tone == designcraft_images::Tone::Bitmap && designcraft_images::is_bitmap(&bytes) => default_black(),
|
||||
None => return false,
|
||||
};
|
||||
(tone, paint)
|
||||
};
|
||||
let Some(coverage) = designcraft_images::decode_rgba(&bytes).and_then(|img| CoverageImage::new(&img)) else { return false };
|
||||
let interpolate = RasterMode::for_standard(self.opts.standard).interpolate;
|
||||
let mask = if self.opts.compress_images && tone == designcraft_images::Tone::Gray { coverage.jpeg(interpolate) } else { None };
|
||||
|
||||
@@ -1102,6 +1102,59 @@ fn a_swatch_colours_a_greyscale_image() {
|
||||
assert!(!s.contains("PANTONE#20Test"), "a colour image keeps its colours");
|
||||
}
|
||||
|
||||
/// A 1-bit (bitmap mode) TIFF with no colour applied (`Fill::none()`) exports with transparent
|
||||
/// white pixels and black ink, not as an opaque white image or JPEG (#3379).
|
||||
#[test]
|
||||
fn uncoloured_one_bit_tiff_exports_with_transparent_white() {
|
||||
// 1-bit WhiteIsZero TIFF, 8×1: first 4 pixels white (0), last 4 pixels black (1).
|
||||
let entries: [(u16, u16, u32); 8] = [(256, 3, 8), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 0), (273, 4, 8), (278, 3, 1), (279, 4, 1)];
|
||||
let mut tiff = b"II*\0".to_vec();
|
||||
tiff.extend(10u32.to_le_bytes());
|
||||
tiff.extend([0b0000_1111u8, 0]);
|
||||
tiff.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
tiff.extend(tag.to_le_bytes());
|
||||
tiff.extend(kind.to_le_bytes());
|
||||
tiff.extend(1u32.to_le_bytes());
|
||||
if kind == 3 {
|
||||
tiff.extend(u16::try_from(value).unwrap().to_le_bytes());
|
||||
tiff.extend([0, 0]);
|
||||
} else {
|
||||
tiff.extend(value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
tiff.extend(0u32.to_le_bytes());
|
||||
|
||||
let mut d = doc_with_text("underneath");
|
||||
place(&mut d, tiff, (8, 1));
|
||||
let expected_mask = vec![0, 0, 0, 0, 255, 255, 255, 255];
|
||||
|
||||
for (standard, compress_images) in [(Standard::None, false), (Standard::None, true), (Standard::PdfX4, false), (Standard::PdfA2b, false)] {
|
||||
let opts = PdfOptions { standard, compress_images, compress: false, created: Some(1_700_000_000), ..Default::default() };
|
||||
let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap_or_else(|e| panic!("{standard:?} compress={compress_images}: {e}"));
|
||||
if standard != Standard::PdfA2b {
|
||||
assert!(r.warnings.is_empty(), "{standard:?} compress={compress_images}: {:?}", r.warnings);
|
||||
}
|
||||
let s = String::from_utf8_lossy(&r.bytes);
|
||||
assert!(s.contains("/SMask"), "{standard:?} compress={compress_images}: white pixels must be masked transparent");
|
||||
assert!(!s.contains("/DCTDecode"), "{standard:?} compress={compress_images}: 1-bit bitmap must not become opaque JPEG");
|
||||
let xobjects = image_xobjects(&r.bytes);
|
||||
assert_eq!(xobjects.len(), 1, "{standard:?} compress={compress_images}: {xobjects:?}");
|
||||
if standard != Standard::PdfA2b {
|
||||
assert_eq!(xobjects[0].0, "DeviceGray", "{standard:?} compress={compress_images}");
|
||||
}
|
||||
assert_eq!(xobjects[0].1, expected_mask, "{standard:?} compress={compress_images}: coverage mask has 0 for white and 255 for black");
|
||||
}
|
||||
// PDF/X-1a flattens the 1-bit bitmap's transparency cleanly with no transparency left.
|
||||
let x1a = export_pdf_with_report(
|
||||
&d,
|
||||
&Cache::new(),
|
||||
&PdfOptions { standard: Standard::PdfX1a, compress: false, created: Some(1_700_000_000), ..Default::default() },
|
||||
)
|
||||
.expect("PDF/X-1a export succeeds");
|
||||
assert!(!String::from_utf8_lossy(&x1a.bytes).contains("/SMask"), "PDF/X-1a flattens soft masks");
|
||||
}
|
||||
|
||||
/// An inline object is painted under its frame's text, as InDesign draws it: a picture whose
|
||||
/// frame reaches down into the next line (a negative Y offset) doesn't hide that line.
|
||||
#[test]
|
||||
|
||||
@@ -64,10 +64,19 @@ fn tone_of(data: &AssetData, wait: bool) -> Prepared<Option<Tone>> {
|
||||
}
|
||||
|
||||
/// `pm` (decoded from `data`) coloured by `fill`, cached per image and on-screen colour; `None`
|
||||
/// when the image keeps its own colours: no swatch, one that no longer exists, a colour image,
|
||||
/// or one whose file can't be had. Without `wait`, an image whose tone isn't known yet is
|
||||
/// [`Prepared::Pending`] while it is found in the background.
|
||||
/// when the image keeps its own colours: a colour image, an uncoloured greyscale image, or one
|
||||
/// whose file can't be had. A 1-bit (bitmap mode) raster always has transparent white pixels and
|
||||
/// draws its black pixels in `[Black]` when no swatch applies. Without `wait`, a coloured image
|
||||
/// whose tone isn't known yet is [`Prepared::Pending`] while it is found in the background.
|
||||
pub(crate) fn colorized(doc: &Document, fill: &Fill, data: &AssetData, pm: &Arc<Pixmap>, wait: bool) -> Prepared<Option<Arc<Pixmap>>> {
|
||||
if crate::images::is_bitmap(data.key()) {
|
||||
let color = (!fill.is_none())
|
||||
.then(|| doc.resolve_color(&fill.swatch, fill.tint))
|
||||
.flatten()
|
||||
.or_else(|| doc.resolve_color(designcraft_color::swatch::BLACK, 1.0))
|
||||
.unwrap_or_else(|| designcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
return Prepared::Ready(Some(coloured(color, Tone::Bitmap, pm)));
|
||||
}
|
||||
if fill.is_none() {
|
||||
return Prepared::Ready(None);
|
||||
}
|
||||
|
||||
@@ -71,6 +71,8 @@ struct Cache {
|
||||
kept_full: std::collections::VecDeque<(SourceKey, u32)>,
|
||||
/// Linked bytes that couldn't be loaded: why, the link generation then, and a stamp.
|
||||
unavailable: HashMap<SourceKey, (Unavailable, u64, u64)>,
|
||||
/// Assets decoded from a 1-bit (bitmap mode) raster, whose white pixels are transparent.
|
||||
bitmaps: HashSet<SourceKey>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
@@ -267,6 +269,25 @@ fn dims_now(data: &AssetData, page: u32) -> Option<(u32, u32)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember that `id` was decoded from a 1-bit (bitmap mode) raster.
|
||||
fn note_bitmap(id: SourceKey, bytes: &[u8]) {
|
||||
if !designcraft_images::is_bitmap(bytes) {
|
||||
return;
|
||||
}
|
||||
with(|c| {
|
||||
if c.bitmaps.len() >= MAX_DIMS {
|
||||
let Cache { bitmaps, map, .. } = c;
|
||||
bitmaps.retain(|k| map.keys().any(|mk| mk.0 == *k));
|
||||
}
|
||||
c.bitmaps.insert(id);
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether `id` was decoded from a 1-bit (bitmap mode) raster.
|
||||
pub(crate) fn is_bitmap(id: SourceKey) -> bool {
|
||||
with(|c| !c.bitmaps.is_empty() && c.bitmaps.contains(&id))
|
||||
}
|
||||
|
||||
/// Decode `bytes` (named by `id`) at full resolution without caching the pixels (its size is
|
||||
/// remembered); a failure marks it bad.
|
||||
fn decode_full(id: SourceKey, bytes: &[u8], page: u32) -> Option<Arc<Pixmap>> {
|
||||
@@ -275,6 +296,9 @@ fn decode_full(id: SourceKey, bytes: &[u8], page: u32) -> Option<Arc<Pixmap>> {
|
||||
log_decode(id);
|
||||
match pm {
|
||||
Some(pm) => {
|
||||
if page == 0 {
|
||||
note_bitmap(id, bytes);
|
||||
}
|
||||
set_dims(id, page, (u32::from(pm.width()), u32::from(pm.height())), true);
|
||||
Some(Arc::new(pm))
|
||||
}
|
||||
@@ -1235,6 +1259,7 @@ fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option<usize
|
||||
None => None,
|
||||
};
|
||||
let p = decode_pixmap_reduced(bytes, shrink)?;
|
||||
note_bitmap(id, bytes);
|
||||
log_decode(id);
|
||||
let p = Arc::new(crop(p, sw, sh)?);
|
||||
store(id, page, shrink, p.clone(), colour);
|
||||
@@ -1275,6 +1300,7 @@ pub fn clear() {
|
||||
c.bad.clear();
|
||||
c.unavailable.clear();
|
||||
c.dims.clear();
|
||||
c.bitmaps.clear();
|
||||
c.kept_full.clear();
|
||||
c.bytes = 0;
|
||||
c.epoch = c.epoch.wrapping_add(1);
|
||||
|
||||
@@ -25,11 +25,14 @@ pub struct ProxyImage {
|
||||
/// A proxy of page `page` of the image or PDF `bytes`, or `None` when it can't be decoded or no
|
||||
/// encoding within [`MAX_BYTES`] was found.
|
||||
pub fn make_proxy(bytes: &[u8], page: u32) -> Option<ProxyImage> {
|
||||
let pm = decode_for_proxy(bytes, page)?;
|
||||
let mut pm = decode_for_proxy(bytes, page)?;
|
||||
let (w, h) = (u32::from(pm.width()), u32::from(pm.height()));
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
if page == 0 && designcraft_images::is_bitmap(bytes) {
|
||||
pm = bitmap_transparent_white(&pm);
|
||||
}
|
||||
let (tw, th) = fit(w, h, MAX_SIDE_PX);
|
||||
let mut cur = if (tw, th) == (w, h) { pm } else { resample(&pm, tw, th)? };
|
||||
let mut quality = JPEG_QUALITY;
|
||||
@@ -115,6 +118,26 @@ fn resample(pm: &Pixmap, tw: u32, th: u32) -> Option<Pixmap> {
|
||||
Some(Pixmap::from_parts(out, tw as u16, th as u16))
|
||||
}
|
||||
|
||||
/// Turn a decoded 1-bit bitmap's white pixels transparent and keep black pixels opaque black
|
||||
/// (with anti-aliased edge pixels from reduced decodes carrying proportional alpha).
|
||||
fn bitmap_transparent_white(pm: &Pixmap) -> Pixmap {
|
||||
let data = pm
|
||||
.data()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
if p.a == 0 {
|
||||
*p
|
||||
} else {
|
||||
let grey = (u16::from(p.r) * 255 / u16::from(p.a)).min(255);
|
||||
let coverage = 255 - grey;
|
||||
let a = ((coverage * u16::from(p.a) + 127) / 255) as u8;
|
||||
vello_cpu::color::PremulRgba8 { r: 0, g: 0, b: 0, a }
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Pixmap::from_parts(data, pm.width(), pm.height())
|
||||
}
|
||||
|
||||
/// Straight RGBA bytes of a premultiplied pixmap, and whether every pixel is opaque.
|
||||
fn unpremultiplied(pm: &Pixmap) -> (Vec<u8>, bool) {
|
||||
let mut out = Vec::with_capacity(pm.data().len().saturating_mul(4));
|
||||
@@ -224,4 +247,32 @@ mod tests {
|
||||
assert_eq!(p.pixels, (MAX_SIDE_PX, 1));
|
||||
assert!(p.data.len() <= MAX_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_bit_tiff_proxy_keeps_white_transparent_as_png() {
|
||||
// 1-bit WhiteIsZero TIFF, 8×1: bits 0..4 white (0), bits 4..8 black (1).
|
||||
let entries: [(u16, u16, u32); 8] = [(256, 3, 8), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 0), (273, 4, 8), (278, 3, 1), (279, 4, 1)];
|
||||
let mut tiff = b"II*\0".to_vec();
|
||||
tiff.extend(10u32.to_le_bytes());
|
||||
tiff.extend([0b0000_1111u8, 0]);
|
||||
tiff.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
tiff.extend(tag.to_le_bytes());
|
||||
tiff.extend(kind.to_le_bytes());
|
||||
tiff.extend(1u32.to_le_bytes());
|
||||
if kind == 3 {
|
||||
tiff.extend(u16::try_from(value).unwrap().to_le_bytes());
|
||||
tiff.extend([0, 0]);
|
||||
} else {
|
||||
tiff.extend(value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
tiff.extend(0u32.to_le_bytes());
|
||||
|
||||
let proxy = make_proxy(&tiff, 0).expect("1-bit TIFF proxy");
|
||||
assert_eq!(proxy.mime, "image/png");
|
||||
let rgba = designcraft_images::decode_rgba(&proxy.data).expect("proxy decodes");
|
||||
assert_eq!(rgba.get_pixel(0, 0).0[3], 0, "white pixels stay transparent in proxy");
|
||||
assert_eq!(rgba.get_pixel(7, 0).0, [0, 0, 0, 255], "black pixels stay opaque black in proxy");
|
||||
}
|
||||
}
|
||||
@@ -112,3 +112,131 @@ fn colour_images_and_missing_swatches_are_left_alone() {
|
||||
assert_eq!(shown(grey, Fill::swatch("Gone")), plain);
|
||||
assert!(plain[0][0] < 10, "the image is drawn: {plain:?}");
|
||||
}
|
||||
|
||||
/// Synthetic 1-bit TIFF (`photometric`: 0 = WhiteIsZero, 1 = BlackIsZero), uncompressed,
|
||||
/// `width` (a multiple of 8) × `height`, every row repeating `row_bytes`.
|
||||
fn one_bit_tiff(width: u32, height: u32, photometric: u32, row_bytes: &[u8]) -> Vec<u8> {
|
||||
let strip: Vec<u8> = std::iter::repeat_n(row_bytes, height as usize).flatten().copied().collect();
|
||||
let ifd_offset = 8u32 + u32::try_from(strip.len()).unwrap();
|
||||
let ifd_offset = ifd_offset + (ifd_offset & 1);
|
||||
let entries: [(u16, u16, u32); 8] = [
|
||||
(256, 3, width),
|
||||
(257, 3, height),
|
||||
(258, 3, 1),
|
||||
(259, 3, 1),
|
||||
(262, 3, photometric),
|
||||
(273, 4, 8),
|
||||
(278, 3, height),
|
||||
(279, 4, u32::try_from(strip.len()).unwrap()),
|
||||
];
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend(ifd_offset.to_le_bytes());
|
||||
t.extend(&strip);
|
||||
if t.len() % 2 == 1 {
|
||||
t.push(0);
|
||||
}
|
||||
t.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
t.extend(tag.to_le_bytes());
|
||||
t.extend(kind.to_le_bytes());
|
||||
t.extend(1u32.to_le_bytes());
|
||||
if kind == 3 {
|
||||
t.extend(u16::try_from(value).unwrap().to_le_bytes());
|
||||
t.extend([0, 0]);
|
||||
} else {
|
||||
t.extend(value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
t.extend(0u32.to_le_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
/// A 1-bit TIFF placed with no content fill (`Fill::none()`) and no frame fill over a cyan
|
||||
/// rectangle behind it: white pixels are transparent (revealing cyan) and black pixels draw
|
||||
/// black, for both WhiteIsZero and BlackIsZero, and also when decoded via the reduced mip path.
|
||||
#[test]
|
||||
fn uncoloured_one_bit_tiff_leaves_white_transparent_over_items_behind() {
|
||||
let render_over_cyan = |file: Vec<u8>, px: (u32, u32), fill: Fill| -> ([u8; 4], [u8; 4]) {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
// Solid cyan backdrop behind the graphic frame.
|
||||
let mut bg = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 260.0, 180.0)));
|
||||
bg.fill = Fill::swatch(CYAN);
|
||||
bg.stroke = Stroke::default();
|
||||
d.insert_item(SpreadRef::Doc(0), bg, None).unwrap();
|
||||
|
||||
let aid = AssetId(d.alloc());
|
||||
d.assets.insert(
|
||||
aid,
|
||||
Arc::new(Asset {
|
||||
page: 0,
|
||||
id: aid,
|
||||
name: "dieline.tif".into(),
|
||||
mime: "image/tiff".into(),
|
||||
link: None,
|
||||
data: designcraft_doc::AssetData::embedded(file),
|
||||
pixels: Some(px),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
// Frame with [None] fill on top of the cyan backdrop.
|
||||
let mut frame = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 260.0, 180.0)));
|
||||
frame.fill = Fill::none();
|
||||
frame.stroke = Stroke::default();
|
||||
frame.content = Content::Graphic(Graphic {
|
||||
layer_options: None,
|
||||
asset: aid,
|
||||
size: (160.0, 80.0),
|
||||
xf: Affine::translate((100.0, 100.0)),
|
||||
clip: None,
|
||||
auto_fit: Default::default(),
|
||||
fit_align: 4,
|
||||
crop: [0.0; 4],
|
||||
wrap: Default::default(),
|
||||
fill,
|
||||
});
|
||||
d.insert_item(SpreadRef::Doc(0), frame, None).unwrap();
|
||||
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 0;
|
||||
let img = r.render_page(&d, &Cache::new(), 0, 1.0, false, &RenderOptions::default()).unwrap();
|
||||
(img.pixel(140, 140), img.pixel(220, 140))
|
||||
};
|
||||
|
||||
let cyan = swatch_rgb(CYAN, 1.0);
|
||||
let black = swatch_rgb(designcraft_color::swatch::BLACK, 1.0);
|
||||
// WhiteIsZero: left half 0 (white -> transparent), right half 1 (black).
|
||||
let white_is_zero = one_bit_tiff(8, 1, 0, &[0b0000_1111]);
|
||||
let (left, right) = render_over_cyan(white_is_zero.clone(), (8, 1), Fill::none());
|
||||
assert!(near(left, cyan), "WhiteIsZero white reveals cyan behind it: {left:?}");
|
||||
assert!(near(right, black), "WhiteIsZero black draws [Black]: {right:?}");
|
||||
|
||||
// Deleted swatch on a 1-bit TIFF also falls back to default black with transparent white.
|
||||
let (left_gone, right_gone) = render_over_cyan(white_is_zero, (8, 1), Fill::swatch("Gone"));
|
||||
assert!(near(left_gone, cyan), "missing swatch keeps white transparent: {left_gone:?}");
|
||||
assert!(near(right_gone, black), "missing swatch draws [Black]: {right_gone:?}");
|
||||
|
||||
// BlackIsZero: left half 1 (white -> transparent), right half 0 (black).
|
||||
let black_is_zero = one_bit_tiff(8, 1, 1, &[0b1111_0000]);
|
||||
let (left, right) = render_over_cyan(black_is_zero, (8, 1), Fill::none());
|
||||
assert!(near(left, cyan), "BlackIsZero white reveals cyan behind it: {left:?}");
|
||||
assert!(near(right, black), "BlackIsZero black draws [Black]: {right:?}");
|
||||
|
||||
// Wide 1-bit WhiteIsZero TIFF rendered at 160 pt wide exercises the reduced TIFF decode path.
|
||||
let mut wide_row = vec![0x00u8; 40];
|
||||
wide_row.extend(std::iter::repeat_n(0xFFu8, 40));
|
||||
let wide = one_bit_tiff(640, 160, 0, &wide_row);
|
||||
let (left, right) = render_over_cyan(wide, (640, 160), Fill::none());
|
||||
assert!(near(left, cyan), "reduced-decode 1-bit TIFF white reveals cyan: {left:?}");
|
||||
assert!(near(right, black), "reduced-decode 1-bit TIFF black draws [Black]: {right:?}");
|
||||
|
||||
// Non-bitmap rasters with Fill::none() keep opaque white (8-bit grey TIFF and opaque B&W GIF).
|
||||
let mut grey_tiff = Vec::new();
|
||||
image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut grey_tiff)).write_image(&[255u8, 0], 2, 1, ExtendedColorType::L8).unwrap();
|
||||
let (left_grey, _) = render_over_cyan(grey_tiff, (2, 1), Fill::none());
|
||||
assert!(left_grey[0] > 240 && left_grey[1] > 240 && left_grey[2] > 240, "8-bit grey white stays opaque: {left_grey:?}");
|
||||
|
||||
let bw_gif = [[255u8, 255, 255, 255], [0, 0, 0, 255]].concat();
|
||||
let (left_gif, _) = render_over_cyan(encode(&bw_gif, 2, ExtendedColorType::Rgba8, true), (2, 1), Fill::none());
|
||||
assert!(left_gif[0] > 240 && left_gif[1] > 240 && left_gif[2] > 240, "opaque B&W GIF white stays opaque: {left_gif:?}");
|
||||
}
|
||||
Reference in new issue
Block a user