Debian Codegraph @

examples/decode.rs

raw symbols SCIP
1 use tiff::decoder::{BufferLayoutPreference, Decoder, DecodingBuffer, DecodingResult};
2
3 fn main() -> Result<(), Box<dyn std::error::Error>> {
4 let Some(image) = std::env::args_os().nth(1) else {
5 eprintln!("Usage: decode FILE");
6 return Ok(());
7 };
8
9 let file = std::fs::File::open(image)?;
10 let io = std::io::BufReader::new(file);
11 let mut reader = Decoder::new(io)?;
12
13 let mut data = DecodingResult::I8(vec![]);
14
15 for i in 0u32.. {
16 let colortype = reader.colortype()?;
17 let dimensions = reader.dimensions()?;
18 let layout = reader.read_image_to_buffer(&mut data)?;
19
20 debug_planes(i, &mut data, &layout, &colortype, dimensions);
21
22 if !reader.more_images() {
23 break;
24 }
25
26 reader.next_image()?
27 }
28
29 Ok(())
30 }
31
32 fn debug_planes(
33 index: u32,
34 data: &mut DecodingResult,
35 layout: &BufferLayoutPreference,
36 colortype: &tiff::ColorType,
37 (width, height): (u32, u32),
38 ) {
39 let (depth, mut tupltype) = match colortype {
40 // Note: we will expand, so this is in fact not BLACKANDWHITE
41 tiff::ColorType::Gray(_) => (1, "GRAYSCALE"),
42 tiff::ColorType::RGB(_) => (3, "RGB"),
43 tiff::ColorType::RGBA(_) => (4, "RGB_ALPHA"),
44 tiff::ColorType::Palette(_) => (1, "PALETTE"),
45 tiff::ColorType::CMYK(_) => (4, "CMYK"),
46 tiff::ColorType::Multiband { num_samples: 2, .. } => (2, "GRAYSCALE_ALPHA"),
47 _ => {
48 eprintln!("Unsupported color type for PAM output: {:?}", colortype);
49 return;
50 }
51 };
52
53 // Number of samples in a line and number of sample lines in the image, depending on whether
54 // they are planar or not. This determines the layout of the image buffer when expanding bit
55 // packed samples to a full byte (we support power-of-two sample sizes, positive and negative,
56 // but only those).
57 let (swidth, sheight) = if layout.planes > 1 {
58 (
59 u64::from(width) * u64::from(colortype.num_samples()),
60 u64::from(height),
61 )
62 } else {
63 (
64 u64::from(width),
65 u64::from(height) * u64::from(colortype.num_samples()),
66 )
67 };
68
69 let mut fallback_buffer;
70 let maxval = match data.as_buffer(0) {
71 // `U8` is also our representation of bit-packed color. PAM uses the smallest number of
72 // *bytes* needed to represent a sample but we must also adhere to maxval. We could explode
73 // them here (e.g. represent 1-bit as `{0, 1}`) but we'd also set `maxval` accordingly and
74 // this requires tupltype to be `BLACKANDWHITE` so introducing a bunch of complexity. If
75 // you want to do that in your real code, go ahead.
76 DecodingBuffer::U8(buf) => match colortype.bit_depth() {
77 8 => u64::from(u8::MAX),
78 4 => {
79 fallback_buffer = vec![0; (swidth * sheight) as usize];
80 expand_4bit(buf, swidth, &mut fallback_buffer);
81 *data = DecodingResult::U8(fallback_buffer);
82 u64::from(u8::MAX)
83 }
84 2 => {
85 fallback_buffer = vec![0; (swidth * sheight) as usize];
86 expand_2bit(buf, swidth, &mut fallback_buffer);
87 *data = DecodingResult::U8(fallback_buffer);
88 u64::from(u8::MAX)
89 }
90 1 => {
91 fallback_buffer = vec![0; (swidth * sheight) as usize];
92 expand_1bit(buf, swidth, &mut fallback_buffer);
93 *data = DecodingResult::U8(fallback_buffer);
94 u64::from(u8::MAX)
95 }
96 _ => {
97 eprintln!(
98 "Unsupported bit depth for U8 buffer: {}",
99 colortype.bit_depth()
100 );
101 return;
102 }
103 },
104 DecodingBuffer::U16(_) => u64::from(u16::MAX),
105 DecodingBuffer::U32(_) => u64::from(u32::MAX),
106 DecodingBuffer::U64(_) => u64::MAX,
107 // Eh, this is a good effort I guess.
108 DecodingBuffer::I8(items) => {
109 items.iter_mut().for_each(|v| *v = 0.max(*v));
110 u64::from(i8::MAX as u8)
111 }
112 DecodingBuffer::I16(items) => {
113 items.iter_mut().for_each(|v| *v = 0.max(*v));
114 u64::from(i16::MAX as u16)
115 }
116 DecodingBuffer::I32(items) => {
117 items.iter_mut().for_each(|v| *v = 0.max(*v));
118 u64::from(i32::MAX as u32)
119 }
120 DecodingBuffer::I64(items) => {
121 items.iter_mut().for_each(|v| *v = 0.max(*v));
122 i64::MAX as u64
123 }
124 // Not supported by PAM.
125 DecodingBuffer::F16(_) | DecodingBuffer::F32(_) | DecodingBuffer::F64(_) => return,
126 };
127
128 let byte_len = if layout.planes > 1 {
129 tupltype = "GRAYSCALE";
130 layout.plane_stride.unwrap().get()
131 } else {
132 data.as_buffer(0).byte_len()
133 };
134
135 // Write out this image's planes to PAM files.
136 let header = format!("P7\nWIDTH {width}\nHEIGHT {height}\nDEPTH {depth}\nMAXVAL {maxval}\nTUPLTYPE {tupltype}\nENDHDR\n");
137
138 for (plane, plane_data) in data
139 .as_buffer(0)
140 .as_bytes_mut()
141 .chunks_exact(byte_len)
142 .enumerate()
143 {
144 let filename = format!("image_{index:03}_plane_{plane:03}.pam");
145 let mut file = std::fs::File::create(filename).expect("Failed to create output file");
146
147 use std::io::Write;
148 file.write_all(header.as_bytes())
149 .expect("Failed to write PAM header");
150 file.write_all(plane_data)
151 .expect("Failed to write PAM data");
152 }
153 }
154
155 /// Put exactly the ith `SCALE`-bit chunk of `val` into the least significant bits.
156 #[inline(always)]
157 fn bits_extract<const SCALE: u8>(val: u8, i: u8) -> u8 {
158 // Shift left to discard high bits, then right to bring desired bits down. This way also
159 // conveniently avoids all cases of overflow.
160 (val << (i * SCALE)) >> (8 - SCALE)
161 }
162
163 fn expand_1bit(from: &[u8], samples_per_padded: u64, into: &mut [u8]) {
164 let stride = samples_per_padded.div_ceil(8);
165
166 let from_row = from.chunks_exact(stride as usize);
167 let into_row = into.chunks_exact_mut(samples_per_padded as usize);
168
169 for (from_row, into_row) in from_row.zip(into_row) {
170 for (into, &from) in into_row.chunks_mut(8).zip(from_row) {
171 let data =
172 core::array::from_fn::<u8, 8, _>(|i| 0xff * bits_extract::<1>(from, i as u8));
173 into.copy_from_slice(&data[..into.len()]);
174 }
175 }
176 }
177
178 fn expand_2bit(from: &[u8], samples_per_padded: u64, into: &mut [u8]) {
179 let stride = samples_per_padded.div_ceil(4);
180
181 let from_row = from.chunks_exact(stride as usize);
182 let into_row = into.chunks_exact_mut(samples_per_padded as usize);
183
184 for (from_row, into_row) in from_row.zip(into_row) {
185 for (into, &from) in into_row.chunks_mut(4).zip(from_row) {
186 let data =
187 core::array::from_fn::<u8, 4, _>(|i| 0xaa * bits_extract::<2>(from, i as u8));
188 into.copy_from_slice(&data[..into.len()]);
189 }
190 }
191 }
192
193 fn expand_4bit(from: &[u8], samples_per_padded: u64, into: &mut [u8]) {
194 let stride = samples_per_padded.div_ceil(2);
195
196 let from_row = from.chunks_exact(stride as usize);
197 let into_row = into.chunks_exact_mut(samples_per_padded as usize);
198
199 for (from_row, into_row) in from_row.zip(into_row) {
200 for (into, &from) in into_row.chunks_mut(2).zip(from_row) {
201 let data =
202 core::array::from_fn::<u8, 2, _>(|i| 0x88 * bits_extract::<4>(from, i as u8));
203 into.copy_from_slice(&data[..into.len()]);
204 }
205 }
206 }