-
Notifications
You must be signed in to change notification settings - Fork 23
/
lib.rs
1553 lines (1375 loc) · 49.7 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::cast_lossless)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cognitive_complexity)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::identity_op)]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::inline_always)]
#![allow(clippy::manual_range_contains)]
#![allow(clippy::many_single_char_names)]
#![allow(clippy::new_without_default)]
#![allow(clippy::new_without_default)]
#![allow(clippy::similar_names)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::trivially_copy_pass_by_ref)]
#![allow(clippy::type_complexity)]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::verbose_bit_mask)]
#![allow(unexpected_cfgs)]
#![deny(clippy::unnecessary_mut_passed)]
#[allow(non_camel_case_types)]
pub mod ffi;
mod rustimpl;
mod zlib;
use crate::rustimpl::chunk_length;
mod error;
pub use crate::error::*;
mod iter;
use crate::iter::{ChunksIterFragile, ITextKeysIter, TextKeysIter};
pub use rgb::bytemuck;
pub use rgb::bytemuck::Pod;
pub use rgb::Rgb as RGB;
pub use rgb::RGBA8 as RGBA;
use std::cmp;
use std::convert::TryInto;
use std::fmt;
use std::fs;
use std::mem;
use std::num::NonZeroU8;
use std::os::raw::c_uint;
use std::os::raw::c_void;
use std::path::Path;
use std::ptr;
use std::slice;
#[doc(inline)]
pub use crate::ffi::ColorType;
#[doc(inline)]
pub use crate::ffi::CompressSettings;
#[doc(inline)]
pub use crate::ffi::DecoderSettings;
#[doc(inline)]
pub use crate::ffi::DecompressSettings;
#[doc(inline)]
pub use crate::ffi::EncoderSettings;
#[doc(hidden)]
pub use crate::ffi::ErrorCode;
#[doc(inline)]
pub use crate::ffi::FilterStrategy;
#[doc(hidden)]
pub use crate::ffi::State;
#[doc(inline)]
pub use crate::ffi::Time;
#[doc(inline)]
pub use crate::ffi::ColorMode;
#[doc(inline)]
pub use crate::ffi::Info;
pub use iter::ChunksIter;
impl ColorMode {
#[inline(always)]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
#[must_use]
pub fn colortype(&self) -> ColorType {
self.colortype
}
#[inline(always)]
pub fn set_colortype(&mut self, color: ColorType) {
self.colortype = color;
}
#[inline(always)]
#[must_use]
pub fn bitdepth(&self) -> u32 {
self.bitdepth
}
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
pub fn set_bitdepth(&mut self, d: u32) {
self.try_set_bitdepth(d).unwrap();
}
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
pub fn try_set_bitdepth(&mut self, d: u32) -> Result<(), Error> {
if d < 1 || (d > 8 && d != 16) {
return Err(Error::new(37));
}
self.bitdepth = d;
Ok(())
}
/// Set color depth to 8-bit palette and set the colors
pub fn set_palette(&mut self, palette: &[RGBA]) -> Result<(), Error> {
self.palette_clear();
for &c in palette {
self.palette_add(c)?;
}
self.colortype = ColorType::PALETTE;
self.try_set_bitdepth(8)?;
Ok(())
}
/// Reset to 0 colors
#[inline]
pub fn palette_clear(&mut self) {
self.palette = None;
self.palettesize = 0;
}
/// add 1 color to the palette
pub fn palette_add(&mut self, p: RGBA) -> Result<(), Error> {
if self.palettesize >= 256 {
return Err(Error::new(38));
}
let pal = self.palette.get_or_insert_with(|| Box::new([RGBA::new(0,0,0,0); 256]));
pal[self.palettesize] = p;
self.palettesize += 1;
Ok(())
}
#[inline]
#[must_use]
pub fn palette(&self) -> &[RGBA] {
let len = self.palettesize;
self.palette.as_deref().and_then(|p| p.get(..len)).unwrap_or_default()
}
#[inline]
pub fn palette_mut(&mut self) -> &mut [RGBA] {
let len = self.palettesize;
self.palette.as_deref_mut().and_then(|p| p.get_mut(..len)).unwrap_or_default()
}
/// get the total amount of bits per pixel, based on colortype and bitdepth in the struct
#[inline(always)]
#[must_use]
pub fn bpp(&self) -> u32 {
self.colortype.bpp(self.bitdepth)
}
#[inline(always)]
#[must_use]
pub fn bpp_(&self) -> NonZeroU8 {
self.colortype.bpp_(self.bitdepth)
}
pub(crate) fn clear_key(&mut self) {
self.key_defined = 0;
}
/// `tRNS` chunk
#[cold]
pub fn set_key(&mut self, r: u16, g: u16, b: u16) {
self.key_defined = 1;
self.key_r = c_uint::from(r);
self.key_g = c_uint::from(g);
self.key_b = c_uint::from(b);
}
#[inline]
pub(crate) fn key(&self) -> Option<(u16, u16, u16)> {
if self.key_defined != 0 {
Some((self.key_r as u16, self.key_g as u16, self.key_b as u16))
} else {
None
}
}
/// get the amount of color channels used, based on colortype in the struct.
/// If a palette is used, it counts as 1 channel.
#[inline(always)]
#[must_use]
pub fn channels(&self) -> u8 {
self.colortype.channels()
}
/// is it a greyscale type? (only colortype 0 or 4)
#[cfg_attr(docsrs, doc(alias = "is_grayscale_type"))]
#[cfg_attr(docsrs, doc(alias = "is_gray"))]
#[inline]
#[must_use]
pub fn is_greyscale_type(&self) -> bool {
self.colortype == ColorType::GREY || self.colortype == ColorType::GREY_ALPHA
}
/// has it got an alpha channel? (only colortype 2 or 6)
#[inline]
#[must_use]
pub fn is_alpha_type(&self) -> bool {
(self.colortype as u32 & 4) != 0
}
/// has it got a palette? (only colortype 3)
#[inline(always)]
#[must_use]
pub fn is_palette_type(&self) -> bool {
self.colortype == ColorType::PALETTE
}
/// only returns true if there is a palette and there is a value in the palette with alpha < 255.
/// Loops through the palette to check this.
#[must_use]
pub fn has_palette_alpha(&self) -> bool {
self.palette().iter().any(|p| p.a < 255)
}
/// Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
/// Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
/// Returns false if the image can only have opaque pixels.
/// In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
/// or if "`key_defined`" is true.
#[must_use]
pub fn can_have_alpha(&self) -> bool {
self.key().is_some() || self.is_alpha_type() || self.has_palette_alpha()
}
/// Returns the byte size of a raw image buffer with given width, height and color mode
#[must_use]
pub fn raw_size(&self, w: u32, h: u32) -> usize {
self.raw_size_opt(w as _, h as _).expect("overflow")
}
#[inline]
fn raw_size_opt(&self, w: u32, h: u32) -> Result<usize, Error> {
let bpp = self.bpp() as usize;
let n = (w as usize).checked_mul(h as usize).ok_or(Error::new(77))?;
let res = (n / 8).checked_mul(bpp).ok_or(Error::new(77))?.checked_add(((n & 7) * bpp + 7) / 8).ok_or(Error::new(77))?;
Ok(res)
}
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
pub(crate) fn raw_size_idat(&self, w: u32, h: u32) -> Option<usize> {
let w = w as usize;
let h = h as usize;
let bpp = self.bpp() as usize;
let line = (w / 8).checked_mul(bpp)?.checked_add(((w & 7) * bpp + 7) / 8)?;
h.checked_mul(line)
}
}
impl Default for ColorMode {
#[inline]
fn default() -> Self {
Self {
key_defined: 0,
key_r: 0,
key_g: 0,
key_b: 0,
colortype: ColorType::RGBA,
bitdepth: 8,
palette: None,
palettesize: 0,
}
}
}
impl ColorType {
/// Create color mode with given type and bitdepth
#[inline]
#[must_use]
pub fn to_color_mode(&self, bitdepth: c_uint) -> ColorMode {
ColorMode {
colortype: *self,
bitdepth,
..ColorMode::default()
}
}
/// channels * bytes per channel = bytes per pixel
#[inline]
#[must_use]
pub fn channels(&self) -> u8 {
match *self {
ColorType::GREY | ColorType::PALETTE => 1,
ColorType::GREY_ALPHA => 2,
ColorType::BGR |
ColorType::RGB => 3,
ColorType::BGRA |
ColorType::BGRX |
ColorType::RGBA => 4,
}
}
}
impl Time {
#[inline(always)]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl Default for Info {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Info {
#[inline]
#[must_use]
pub fn new() -> Self {
Self {
color: ColorMode::new(),
interlace_method: 0,
background_defined: false, background_r: 0, background_g: 0, background_b: 0,
time_defined: false, time: Time::new(),
always_zero_for_ffi_hack: [0, 0, 0],
unknown_chunks: [Box::new(Vec::new()), Box::new(Vec::new()), Box::new(Vec::new())],
texts: Vec::new(),
itexts: Vec::new(),
phys_defined: false, phys_x: 0, phys_y: 0, phys_unit: 0,
}
}
#[inline(always)]
#[must_use]
pub fn text_keys(&self) -> TextKeysIter<'_> {
TextKeysIter { s: &self.texts }
}
#[deprecated(note = "use text_keys")]
#[must_use]
pub fn text_keys_cstr(&self) -> TextKeysIter<'_> {
self.text_keys()
}
#[inline(always)]
#[must_use]
pub fn itext_keys(&self) -> ITextKeysIter<'_> {
ITextKeysIter { s: &self.itexts }
}
/// use this to clear the texts again after you filled them in
#[inline]
pub fn clear_text(&mut self) {
self.texts = Vec::new();
self.itexts = Vec::new();
}
/// push back both texts at once
#[inline]
pub fn add_text(&mut self, key: &str, str: &str) -> Result<(), Error> {
self.push_text(key.as_bytes(), str.as_bytes())
}
/// use this to clear the itexts again after you filled them in
#[inline]
pub fn clear_itext(&mut self) {
self.itexts = Vec::new();
}
/// push back the 4 texts of 1 chunk at once
pub fn add_itext(&mut self, key: &str, langtag: &str, transkey: &str, text: &str) -> Result<(), Error> {
self.push_itext(
key.as_bytes(),
langtag.as_bytes(),
transkey.as_bytes(),
text.as_bytes(),
)
}
/// Add literal PNG-data chunk unmodified to the unknown chunks
#[inline]
pub fn append_chunk(&mut self, position: ChunkPosition, chunk: ChunkRef<'_>) -> Result<(), Error> {
self.unknown_chunks[position as usize].extend_from_slice(chunk.data);
Ok(())
}
/// Add custom chunk data to the file (if writing one)
pub fn create_chunk<C: AsRef<[u8]>>(&mut self, position: ChunkPosition, chtype: C, data: &[u8]) -> Result<(), Error> {
let chtype = chtype.as_ref();
let chtype = match chtype.try_into() {
Ok(c) => c,
Err(_) => return Err(Error::new(67)),
};
let mut ch = rustimpl::ChunkBuilder::new(&mut self.unknown_chunks[position as usize], &chtype);
ch.extend_from_slice(data)?;
ch.finish()
}
/// Uses linear search to find a given chunk. You can use `b"PLTE"` syntax.
pub fn get<NameBytes: AsRef<[u8]>>(&self, index: NameBytes) -> Option<ChunkRef<'_>> {
let index = index.as_ref();
self.try_unknown_chunks(ChunkPosition::IHDR)
.chain(self.try_unknown_chunks(ChunkPosition::PLTE))
.chain(self.try_unknown_chunks(ChunkPosition::IDAT))
.filter_map(|c| c.ok())
.find(|c| c.is_type(index))
}
#[deprecated(note = "use try_unknown_chunks")]
#[must_use]
pub fn unknown_chunks(&self, position: ChunkPosition) -> ChunksIterFragile<'_> {
ChunksIterFragile::new(&self.unknown_chunks[position as usize])
}
/// Iterate over chunks that aren't part of image data. Only available if `remember_unknown_chunks` was set.
#[inline]
#[must_use]
pub fn try_unknown_chunks(&self, position: ChunkPosition) -> ChunksIter<'_> {
ChunksIter::new(&self.unknown_chunks[position as usize])
}
}
#[derive(Clone, Debug, Default)]
/// Make an image with custom settings
pub struct Encoder {
state: State,
predefined_filters: Option<Box<[u8]>>,
}
impl Encoder {
#[inline(always)]
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Switch color mode to 8-bit palette and set the colors
pub fn set_palette(&mut self, palette: &[RGBA]) -> Result<(), Error> {
self.state.info_raw_mut().set_palette(palette)?;
self.state.info_png_mut().color.set_palette(palette)
}
/// If true, convert to output format
#[inline(always)]
pub fn set_auto_convert(&mut self, mode: bool) {
self.state.set_auto_convert(mode);
}
/// `palette_filter_zero` controls filtering for low-bitdepth images
#[inline(always)]
pub fn set_filter_strategy(&mut self, mode: FilterStrategy, palette_filter_zero: bool) {
if mode != FilterStrategy::PREDEFINED {
self.predefined_filters = None;
}
self.state.set_filter_strategy(mode, palette_filter_zero);
}
/// Filters are 0-5, one per row.
/// <https://www.w3.org/TR/PNG-Filters.html>
#[inline(always)]
pub fn set_predefined_filters(&mut self, filters: impl Into<Box<[u8]>>) {
self.state.set_filter_strategy(FilterStrategy::PREDEFINED, true);
let filters = filters.into();
self.settings_mut().predefined_filters = filters.as_ptr();
self.predefined_filters = Some(filters);
}
/// gzip text metadata
#[inline(always)]
pub fn set_text_compression(&mut self, compr: bool) {
self.state.encoder.text_compression = compr;
}
/// Compress using another zlib implementation. It's gzip header + deflate + adler32 checksum.
#[inline(always)]
#[allow(deprecated)]
pub fn set_custom_zlib(&mut self, callback: ffi::custom_compress_callback, context: *const c_void) {
self.state.encoder.zlibsettings.custom_zlib = callback;
self.state.encoder.zlibsettings.custom_context = context;
}
/// Compress using another deflate implementation. It's just deflate, without headers or checksum.
#[inline(always)]
#[allow(deprecated)]
pub fn set_custom_deflate(&mut self, callback: ffi::custom_compress_callback, context: *const c_void) {
self.state.encoder.zlibsettings.custom_deflate = callback;
self.state.encoder.zlibsettings.custom_context = context;
}
#[inline(always)]
#[must_use]
pub fn info_raw(&self) -> &ColorMode {
self.state.info_raw()
}
#[inline(always)]
/// Color mode of the source bytes to be encoded
pub fn info_raw_mut(&mut self) -> &mut ColorMode {
self.state.info_raw_mut()
}
#[inline(always)]
#[must_use]
pub fn info_png(&self) -> &Info {
self.state.info_png()
}
/// Color mode of the file to be created
#[inline(always)]
#[must_use]
pub fn info_png_mut(&mut self) -> &mut Info {
self.state.info_png_mut()
}
#[inline(always)]
#[allow(deprecated)]
#[track_caller]
/// Takes any pixel type, but for safety the type has to be marked as "plain old data"
pub fn encode<PixelType: Pod>(&self, image: &[PixelType], w: usize, h: usize) -> Result<Vec<u8>, Error> {
if let Some(filters) = &self.predefined_filters {
if filters.len() < h {
return Err(Error::new(88))
}
}
self.state.encode(image, w, h)
}
#[inline(always)]
#[allow(deprecated)]
/// Takes any pixel type, but for safety the type has to be marked as "plain old data"
pub fn encode_file<PixelType: Pod, P: AsRef<Path>>(&self, filepath: P, image: &[PixelType], w: usize, h: usize) -> Result<(), Error> {
if let Some(filters) = &self.predefined_filters {
if filters.len() < h {
return Err(Error::new(88));
}
}
self.state.encode_file(filepath, image, w, h)
}
#[inline(always)]
pub fn settings_mut(&mut self) -> &mut EncoderSettings {
&mut self.state.encoder
}
}
#[derive(Clone, Debug, Default)]
/// Read an image with custom settings
pub struct Decoder {
pub(crate) state: State,
}
impl Decoder {
#[inline(always)]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
#[must_use]
pub fn info_raw(&self) -> &ColorMode {
self.state.info_raw()
}
#[inline(always)]
/// Preferred color mode for decoding
pub fn info_raw_mut(&mut self) -> &mut ColorMode {
self.state.info_raw_mut()
}
#[inline(always)]
/// Actual color mode of the decoded image or inspected file
#[must_use]
pub fn info_png(&self) -> &Info {
self.state.info_png()
}
#[inline(always)]
pub fn info_png_mut(&mut self) -> &mut Info {
self.state.info_png_mut()
}
/// whether to convert the PNG to the color type you want. Default: yes
#[inline(always)]
pub fn color_convert(&mut self, true_or_false: bool) {
self.state.color_convert(true_or_false);
}
/// if false but `remember_unknown_chunks` is true, they're stored in the unknown chunks.
#[inline(always)]
pub fn read_text_chunks(&mut self, true_or_false: bool) {
self.state.read_text_chunks(true_or_false);
}
/// store all bytes from unknown chunks in the `Info` (off by default, useful for a png editor)
#[inline(always)]
pub fn remember_unknown_chunks(&mut self, true_or_false: bool) {
self.state.remember_unknown_chunks(true_or_false);
}
/// Decompress ICC profile from `iCCP` chunk. Only available if `remember_unknown_chunks` was set.
#[inline(always)]
pub fn get_icc(&self) -> Result<Vec<u8>, Error> {
self.state.get_icc()
}
/// Load PNG from buffer using Decoder's settings
///
/// ```no_run
/// # use lodepng::*; let mut state = Decoder::new();
/// # let slice = [0u8]; #[allow(unused_variables)] fn do_stuff<T>(_buf: T) {}
///
/// state.info_raw_mut().colortype = ColorType::RGBA;
/// match state.decode(&slice) {
/// Ok(Image::RGBA(with_alpha)) => do_stuff(with_alpha),
/// _ => panic!("¯\\_(ツ)_/¯")
/// }
/// ```
#[inline(always)]
#[allow(deprecated)]
pub fn decode<Bytes: AsRef<[u8]>>(&mut self, input: Bytes) -> Result<Image, Error> {
self.state.decode(input)
}
/// Decode a file from disk using Decoder's settings
#[allow(deprecated)]
#[inline(always)]
pub fn decode_file<P: AsRef<Path>>(&mut self, filepath: P) -> Result<Image, Error> {
self.state.decode_file(filepath)
}
/// Updates `info_png`. Returns (width, height)
#[allow(deprecated)]
#[inline(always)]
pub fn inspect(&mut self, input: &[u8]) -> Result<(usize, usize), Error> {
self.state.inspect(input)
}
/// use custom zlib decoder instead of built in one
#[inline(always)]
pub fn set_custom_zlib(&mut self, callback: ffi::custom_decompress_callback, context: *const c_void) {
self.state.decoder.zlibsettings.custom_zlib = callback;
self.state.decoder.zlibsettings.custom_context = context;
}
/// use custom deflate decoder instead of built in one.
///
/// If `custom_zlib` is used, `custom_inflate` is ignored since only the built in zlib function will call `custom_inflate`
#[inline(always)]
pub fn set_custom_inflate(&mut self, callback: ffi::custom_decompress_callback, context: *const c_void) {
self.state.decoder.zlibsettings.custom_inflate = callback;
self.state.decoder.zlibsettings.custom_context = context;
}
}
impl State {
#[deprecated(note = "Use Decoder or Encoder type instead")]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
pub fn set_auto_convert(&mut self, mode: bool) {
self.encoder.auto_convert = mode;
}
#[inline(always)]
pub fn set_filter_strategy(&mut self, mode: FilterStrategy, palette_filter_zero: bool) {
self.encoder.filter_strategy = mode;
self.encoder.filter_palette_zero = palette_filter_zero;
}
/// See `Encoder`
#[deprecated(note = "use flate2 crate features instead")]
#[allow(deprecated)]
pub fn set_custom_zlib(&mut self, callback: ffi::custom_compress_callback, context: *const c_void) {
self.encoder.zlibsettings.custom_zlib = callback;
self.encoder.zlibsettings.custom_context = context;
}
/// See `Encoder`
#[deprecated(note = "use flate2 crate features instead")]
#[allow(deprecated)]
pub fn set_custom_deflate(&mut self, callback: ffi::custom_compress_callback, context: *const c_void) {
self.encoder.zlibsettings.custom_deflate = callback;
self.encoder.zlibsettings.custom_context = context;
}
#[inline(always)]
#[must_use]
pub fn info_raw(&self) -> &ColorMode {
&self.info_raw
}
#[inline(always)]
pub fn info_raw_mut(&mut self) -> &mut ColorMode {
&mut self.info_raw
}
#[inline(always)]
#[must_use]
pub fn info_png(&self) -> &Info {
&self.info_png
}
#[inline(always)]
pub fn info_png_mut(&mut self) -> &mut Info {
&mut self.info_png
}
/// whether to convert the PNG to the color type you want. Default: yes
#[inline(always)]
pub fn color_convert(&mut self, true_or_false: bool) {
self.decoder.color_convert = true_or_false;
}
/// if false but `remember_unknown_chunks` is true, they're stored in the unknown chunks.
#[inline(always)]
pub fn read_text_chunks(&mut self, true_or_false: bool) {
self.decoder.read_text_chunks = true_or_false;
}
/// store all bytes from unknown chunks in the `Info` (off by default, useful for a png editor)
#[inline(always)]
pub fn remember_unknown_chunks(&mut self, true_or_false: bool) {
self.decoder.remember_unknown_chunks = true_or_false;
}
/// Decompress ICC profile from `iCCP` chunk. Only available if `remember_unknown_chunks` was set.
pub fn get_icc(&self) -> Result<Vec<u8>, Error> {
let iccp = self.info_png().get("iCCP");
if iccp.is_none() {
return Err(Error::new(89));
}
let iccp = iccp.as_ref().unwrap().data();
if iccp.first().copied().unwrap_or(255) == 0 { // text min length is 1
return Err(Error::new(89));
}
let name_len = cmp::min(iccp.len(), 80); // skip name
for i in 0..name_len {
if iccp[i] == 0 { // string terminator
if iccp.get(i+1).copied().unwrap_or(255) != 0 { // compression type
return Err(Error::new(72));
}
return zlib::decompress(&iccp[i+2 ..], &self.decoder.zlibsettings);
}
}
Err(Error::new(75))
}
/// Load PNG from buffer using State's settings
///
/// ```no_run
/// # use lodepng::*; let mut state = Decoder::new();
/// # let slice = [0u8]; #[allow(unused_variables)] fn do_stuff<T>(_buf: T) {}
///
/// state.info_raw_mut().colortype = ColorType::RGBA;
/// match state.decode(&slice) {
/// Ok(Image::RGBA(with_alpha)) => do_stuff(with_alpha),
/// _ => panic!("¯\\_(ツ)_/¯")
/// }
/// ```
#[deprecated(note = "Use Decoder type instead of State")]
pub fn decode<Bytes: AsRef<[u8]>>(&mut self, input: Bytes) -> Result<Image, Error> {
let input = input.as_ref();
let (data, w, h) = rustimpl::lodepng_decode(self, input)?;
new_bitmap(data, w, h, self.info_raw.colortype, self.info_raw.bitdepth)
}
#[deprecated(note = "Use Decoder type instead of State")]
#[allow(deprecated)]
#[inline]
pub fn decode_file<P: AsRef<Path>>(&mut self, filepath: P) -> Result<Image, Error> {
self.decode(&fs::read(filepath)?)
}
/// Updates `info_png`. Returns (width, height)
#[deprecated(note = "Use Decoder type instead of State")]
#[inline]
pub fn inspect(&mut self, input: &[u8]) -> Result<(usize, usize), Error> {
let (info, w, h) = rustimpl::lodepng_inspect(&self.decoder, input, true)?;
self.info_png = info;
Ok((w as _, h as _))
}
#[deprecated(note = "Use Encoder type instead of State")]
#[track_caller]
pub fn encode<PixelType: Pod>(&self, image: &[PixelType], w: usize, h: usize) -> Result<Vec<u8>, Error> {
let w = w.try_into().map_err(|_| Error::new(93))?;
let h = h.try_into().map_err(|_| Error::new(93))?;
let image = buffer_for_type(image, w, h, self.info_raw.colortype, self.info_raw.bitdepth)?;
rustimpl::lodepng_encode(image, w, h, self)
}
#[deprecated(note = "Use Encoder type instead of State")]
#[allow(deprecated)]
#[inline]
#[track_caller]
pub fn encode_file<PixelType: Pod, P: AsRef<Path>>(&self, filepath: P, image: &[PixelType], w: usize, h: usize) -> Result<(), Error> {
let buf = self.encode(image, w, h)?;
fs::write(filepath, buf)?;
Ok(())
}
}
impl Default for State {
fn default() -> Self {
Self {
decoder: DecoderSettings::new(),
encoder: EncoderSettings::new(),
info_raw: ColorMode::new(),
info_png: Info::new(),
error: ErrorCode(1),
}
}
}
#[cfg_attr(docsrs, doc(alias = "Gray"))]
pub use rgb::Gray as Grey;
#[cfg_attr(docsrs, doc(alias = "GrayAlpha"))]
pub use rgb::alt::GrayAlpha as GreyAlpha;
/// Bitmap types.
///
/// Images with >=8bpp are stored with pixel per vec element.
/// Images with <8bpp are represented as a bunch of bytes, with multiple pixels per byte.
///
/// Check `decoder.info_raw()` for more info about the image type.
#[derive(Debug)]
pub enum Image {
/// Bytes of the image. See bpp how many pixels per element there are
RawData(Bitmap<u8>),
#[cfg_attr(docsrs, doc(alias = "Gray"))]
Grey(Bitmap<Grey<u8>>),
#[cfg_attr(docsrs, doc(alias = "Gray16"))]
Grey16(Bitmap<Grey<u16>>),
#[cfg_attr(docsrs, doc(alias = "GrayAlpha"))]
GreyAlpha(Bitmap<GreyAlpha<u8>>),
#[cfg_attr(docsrs, doc(alias = "GrayAlpha16"))]
GreyAlpha16(Bitmap<GreyAlpha<u16>>),
#[cfg_attr(docsrs, doc(alias = "RGBA8"))]
RGBA(Bitmap<RGBA>),
#[cfg_attr(docsrs, doc(alias = "RGB8"))]
RGB(Bitmap<rgb::Rgb<u8>>),
RGBA16(Bitmap<rgb::Rgba<u16>>),
RGB16(Bitmap<RGB<u16>>),
}
impl Image {
#[must_use] pub fn width(&self) -> usize {
match self {
Self::RawData(bitmap) => bitmap.width,
Self::Grey(bitmap) => bitmap.width,
Self::Grey16(bitmap) => bitmap.width,
Self::GreyAlpha(bitmap) => bitmap.width,
Self::GreyAlpha16(bitmap) => bitmap.width,
Self::RGBA(bitmap) => bitmap.width,
Self::RGB(bitmap) => bitmap.width,
Self::RGBA16(bitmap) => bitmap.width,
Self::RGB16(bitmap) => bitmap.width,
}
}
#[must_use] pub fn height(&self) -> usize {
match self {
Self::RawData(bitmap) => bitmap.height,
Self::Grey(bitmap) => bitmap.height,
Self::Grey16(bitmap) => bitmap.height,
Self::GreyAlpha(bitmap) => bitmap.height,
Self::GreyAlpha16(bitmap) => bitmap.height,
Self::RGBA(bitmap) => bitmap.height,
Self::RGB(bitmap) => bitmap.height,
Self::RGBA16(bitmap) => bitmap.height,
Self::RGB16(bitmap) => bitmap.height,
}
}
/// Raw bytes of the underlying buffer
#[must_use] pub fn bytes(&self) -> &[u8] {
use rgb::bytemuck::cast_slice;
match self {
Self::RawData(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
slice
},
Self::Grey(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height);
slice
},
Self::Grey16(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 2);
slice
},
Self::GreyAlpha(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 2);
slice
},
Self::GreyAlpha16(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 4);
slice
},
Self::RGBA(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 4);
slice
},
Self::RGB(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 3);
slice
},
Self::RGBA16(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 8);
slice
},
Self::RGB16(bitmap) => {
let slice = cast_slice(&bitmap.buffer);
debug_assert_eq!(slice.len(), bitmap.width * bitmap.height * 6);
slice
},
}
}
}
/// Position in the file section after…
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum ChunkPosition {
IHDR = 0,
PLTE = 1,
IDAT = 2,
}
/// Low-level representation of an image
///
/// Takes any pixel type, but for safety the type has to be marked as "plain old data"
#[derive(Clone)]
pub struct Bitmap<PixelType> {
/// Raw bitmap memory. Layout depends on color mode and bitdepth used to create it.
///
/// * For RGB/RGBA images one element is one pixel.
/// * For <8bpp images pixels are packed, so raw bytes are exposed and you need to do bit-twiddling youself
pub buffer: Vec<PixelType>,
/// Width in pixels
pub width: usize,
/// Height in pixels
pub height: usize,
}
impl<PixelType: Pod> Bitmap<PixelType> {
/// Convert Vec<u8> to Vec<PixelType>
#[cfg_attr(debug_assertions, track_caller)]
fn from_buffer(buffer: Vec<u8>, width: usize, height: usize) -> Result<Self> {
let area = width.checked_mul(height).ok_or(Error::new(77))?;
// Can only cast Vec if alignment doesn't change, and capacity is a round number of pixels
let is_safe_to_transmute = 1 == std::mem::align_of::<PixelType>() &&
0 == buffer.capacity() % std::mem::align_of::<PixelType>() &&
0 == buffer.len() % std::mem::align_of::<PixelType>();
let buffer = if is_safe_to_transmute {
unsafe {
let mut buffer = std::mem::ManuallyDrop::new(buffer);
Vec::from_raw_parts(buffer.as_mut_ptr().cast::<PixelType>(),
buffer.len() / std::mem::size_of::<PixelType>(),
buffer.capacity() / std::mem::size_of::<PixelType>())
}
} else {
// if it's not properly aligned (e.g. reading RGB<u16>), do it the hard way
let mut out = Vec::<PixelType>::new();
out.try_reserve_exact(area)?;
let dest = out.spare_capacity_mut();
assert!(dest.len() >= area);
unsafe {
ptr::copy_nonoverlapping(buffer.as_ptr(), dest.as_mut_ptr().cast::<u8>(), buffer.len());
out.set_len(area);
}
out
};
if buffer.len() < area {