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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#![crate_name = "lodepng"]
#![crate_type = "lib"]
extern crate libc;
extern crate rgb;
extern crate c_vec;
pub use rgb::RGB;
pub use rgb::RGBA;
use libc::{c_char, c_uchar, c_uint, size_t, c_void, free};
use std::fmt;
use std::mem;
use std::fs::File;
use std::io::Write;
use std::io::Read;
use c_vec::CVec;
use std::path::Path;
pub use ffi::ColorType;
pub use ffi::ColorType::{LCT_GREY, LCT_RGB, LCT_PALETTE, LCT_GREY_ALPHA, LCT_RGBA};
pub use ffi::CompressSettings;
pub use ffi::Time;
pub use ffi::DecoderSettings;
pub use ffi::FilterStrategy;
pub use ffi::FilterStrategy::{LFS_ZERO, LFS_MINSUM, LFS_ENTROPY, LFS_BRUTE_FORCE, LFS_PREDEFINED};
pub use ffi::AutoConvert;
pub use ffi::AutoConvert::{LAC_NO, LAC_ALPHA, LAC_AUTO, LAC_AUTO_NO_NIBBLES, LAC_AUTO_NO_PALETTE, LAC_AUTO_NO_NIBBLES_NO_PALETTE};
pub use ffi::EncoderSettings;
pub use ffi::Error;
pub struct ColorMode {
data: ffi::ColorMode,
}
impl ColorMode {
pub fn new() -> ColorMode {
unsafe {
let mut mode = mem::zeroed();
ffi::lodepng_color_mode_init(&mut mode);
return ColorMode{data:mode};
}
}
pub fn colortype(&self) -> ColorType {
self.data.colortype
}
pub fn bitdepth(&self) -> u32 {
self.data.bitdepth
}
pub fn palette_clear(&mut self) {
unsafe {
ffi::lodepng_palette_clear(&mut self.data)
}
}
pub fn palette_add(&mut self, r: u8, g: u8, b: u8, a: u8) -> Option<Error> {
unsafe {
ffi::lodepng_palette_add(&mut self.data, r, g, b, a).to_result().err()
}
}
pub fn bpp(&self) -> u32 {
unsafe {
ffi::lodepng_get_bpp(&self.data) as u32
}
}
pub fn channels(&self) -> u32 {
unsafe {
ffi::lodepng_get_channels(&self.data) as u32
}
}
pub fn is_greyscale_type(&self) -> bool {
unsafe {
ffi::lodepng_is_greyscale_type(&self.data) != 0
}
}
pub fn is_alpha_type(&self) -> bool {
unsafe {
ffi::lodepng_is_alpha_type(&self.data) != 0
}
}
pub fn is_palette_type(&self) -> bool {
unsafe {
ffi::lodepng_is_palette_type(&self.data) != 0
}
}
pub fn has_palette_alpha(&self) -> bool {
unsafe {
ffi::lodepng_has_palette_alpha(&self.data) != 0
}
}
pub fn can_have_alpha(&self) -> bool {
unsafe {
ffi::lodepng_can_have_alpha(&self.data) != 0
}
}
pub fn raw_size(&self, w: c_uint, h: c_uint) -> usize {
unsafe {
ffi::lodepng_get_raw_size(w, h, &self.data) as usize
}
}
}
impl Drop for ColorMode {
fn drop(&mut self) {
unsafe {
ffi::lodepng_color_mode_cleanup(&mut self.data)
}
}
}
impl Clone for ColorMode {
fn clone(&self) -> ColorMode {
unsafe {
let mut dest = ColorMode{ data: mem::zeroed() };
ffi::lodepng_color_mode_copy(&mut dest.data, &self.data).to_result().unwrap();
return dest;
}
}
}
pub struct Info {
data: ffi::Info,
}
impl Info {
pub fn new() -> Info {
unsafe {
let mut info = Info{ data: mem::zeroed() };
ffi::lodepng_info_init(&mut info.data);
return info;
}
}
pub fn clear_text(&mut self) {
unsafe {
ffi::lodepng_clear_text(&mut self.data)
}
}
pub fn add_text(&mut self, key: *const c_char, str: *const c_char) -> Error {
unsafe {
ffi::lodepng_add_text(&mut self.data, key, str)
}
}
pub fn clear_itext(&mut self) {
unsafe {
ffi::lodepng_clear_itext(&mut self.data)
}
}
pub fn add_itext(&mut self, key: *const c_char, langtag: *const c_char, transkey: *const c_char, str: *const c_char) -> Error {
unsafe {
ffi::lodepng_add_itext(&mut self.data, key, langtag, transkey, str)
}
}
}
impl Drop for Info {
fn drop(&mut self) {
unsafe {
ffi::lodepng_info_cleanup(&mut self.data)
}
}
}
impl Clone for Info {
fn clone(&self) -> Info {
unsafe {
let mut dest = Info{ data:mem::zeroed() };
ffi::lodepng_info_copy(&mut dest.data, &self.data).to_result().unwrap();
return dest;
}
}
}
pub struct State {
data: ffi::State,
}
impl State {
pub fn new() -> State {
unsafe {
let mut state = State { data:mem::zeroed() };
ffi::lodepng_state_init(&mut state.data);
return state;
}
}
pub fn info_raw(&mut self) -> &mut ffi::ColorMode {
return &mut self.data.info_raw;
}
pub fn info_png(&mut self) -> &mut ffi::Info {
return &mut self.data.info_png;
}
pub fn decode(&mut self, input: &[u8]) -> Result<::Image, Error> {
unsafe {
let mut out = mem::zeroed();
let mut w = 0;
let mut h = 0;
try!(ffi::lodepng_decode(&mut out, &mut w, &mut h, &mut self.data, input.as_ptr(), input.len() as size_t).to_result());
Ok(::new_bitmap(out, w as usize, h as usize, self.data.info_raw.colortype, self.data.info_raw.bitdepth))
}
}
pub fn inspect(&mut self, input: &[u8]) -> Result<(usize, usize), Error> {
unsafe {
let mut w = 0;
let mut h = 0;
match ffi::lodepng_inspect(&mut w, &mut h, &mut self.data, input.as_ptr(), input.len() as size_t) {
Error(0) => Ok((w as usize, h as usize)),
err => Err(err)
}
}
}
pub fn encode<PixelType>(&mut self, image: &[PixelType], w: usize, h: usize) -> Result<CVec<u8>, Error> {
unsafe {
let mut out = mem::zeroed();
let mut outsize = 0;
try!(::with_buffer_for_type(image, w, h, self.data.info_raw.colortype, self.data.info_raw.bitdepth, |ptr| {
ffi::lodepng_encode(&mut out, &mut outsize, ptr, w as c_uint, h as c_uint, &mut self.data)
}).to_result());
Ok(::cvec_with_free(out, outsize as usize))
}
}
pub fn encode_file<PixelType, P: AsRef<Path>>(&mut self, filepath: P, image: &[PixelType], w: usize, h: usize) -> Result<(), Error> {
let buf = try!(self.encode(image, w, h));
::save_file(filepath, buf.as_cslice().as_ref())
}
}
impl Drop for State {
fn drop(&mut self) {
unsafe {
ffi::lodepng_state_cleanup(&mut self.data)
}
}
}
impl Clone for State {
fn clone(&self) -> State {
unsafe {
let mut dest = State{ data:mem::zeroed() };
ffi::lodepng_state_copy(&mut dest.data, &self.data);
return dest;
}
}
}
#[allow(non_camel_case_types)]
pub mod ffi {
use libc::{c_char, c_uchar, c_uint, c_void, size_t};
use std::mem;
pub use c_vec::CVec;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Error(pub c_uint);
impl Error {
pub fn as_str(&self) -> &'static str {
unsafe {
let cstr = ::std::ffi::CStr::from_ptr(lodepng_error_text(self.0) as *const _);
::std::str::from_utf8(cstr.to_bytes()).unwrap()
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum ColorType {
LCT_GREY = 0,
LCT_RGB = 2,
LCT_PALETTE = 3,
LCT_GREY_ALPHA = 4,
LCT_RGBA = 6,
}
#[repr(C)]
pub struct ColorMode {
pub colortype: ColorType,
pub bitdepth: c_uint,
pub palette: *const ::RGBA<u8>,
pub palettesize: size_t,
key_defined: c_uint,
key_r: c_uint,
key_g: c_uint,
key_b: c_uint,
}
impl ColorType {
pub fn to_color_mode(&self, bitdepth: c_uint) -> super::ColorMode {
unsafe {
super::ColorMode { data: ColorMode{
colortype: *self,
bitdepth: bitdepth,
.. mem::zeroed()
}}
}
}
}
#[repr(C)]
struct DecompressSettings {
pub ignore_adler32: c_uint,
pub custom_zlib: ::std::option::Option<extern "C" fn
(arg1: *mut *mut c_uchar,
arg2: *mut size_t,
arg3: *const c_uchar,
arg4: size_t,
arg5: *const DecompressSettings)
-> c_uint>,
pub custom_inflate: ::std::option::Option<extern "C" fn
(arg1: *mut *mut c_uchar,
arg2: *mut size_t,
arg3: *const c_uchar,
arg4: size_t,
arg5: *const DecompressSettings)
-> c_uint>,
pub custom_context: *const c_void,
}
#[repr(C)]
#[allow(missing_copy_implementations)]
pub struct CompressSettings {
pub btype: c_uint,
pub use_lz77: c_uint,
pub windowsize: c_uint,
pub minmatch: c_uint,
pub nicematch: c_uint,
pub lazymatching: c_uint,
pub custom_zlib: ::std::option::Option<extern "C" fn
(arg1: *mut *mut c_uchar,
arg2: *mut size_t,
arg3: *const c_uchar,
arg4: size_t,
arg5: *const CompressSettings)
-> c_uint>,
pub custom_deflate: ::std::option::Option<extern "C" fn
(arg1: *mut *mut c_uchar,
arg2: *mut size_t,
arg3: *const c_uchar,
arg4: size_t,
arg5: *const CompressSettings)
-> c_uint>,
pub custom_context: *const c_void,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct Time {
pub year: c_uint,
pub month: c_uint,
pub day: c_uint,
pub hour: c_uint,
pub minute: c_uint,
pub second: c_uint,
}
#[repr(C)]
pub struct Info {
pub compression_method: c_uint,
pub filter_method: c_uint,
pub interlace_method: c_uint,
pub color: ColorMode,
pub background_defined: c_uint,
pub background_r: c_uint,
pub background_g: c_uint,
pub background_b: c_uint,
text_num: size_t,
text_keys: *const *const c_char,
text_strings: *const *const c_char,
itext_num: size_t,
itext_keys: *const *const c_char,
itext_langtags: *const *const c_char,
itext_transkeys: *const *const c_char,
itext_strings: *const *const c_char,
pub time_defined: c_uint,
pub time: Time,
pub phys_defined: c_uint,
pub phys_x: c_uint,
pub phys_y: c_uint,
pub phys_unit: c_uint,
unknown_chunks_data: [*const c_uchar; 3],
unknown_chunks_size: [*const size_t; 3],
}
#[repr(C)]
pub struct DecoderSettings {
zlibsettings: DecompressSettings,
pub ignore_crc: c_uint,
pub fix_png: c_uint,
pub color_convert: c_uint,
read_text_chunks: c_uint,
remember_unknown_chunks: c_uint,
}
impl DecoderSettings {
pub fn new() -> DecoderSettings {
unsafe {
let mut settings = ::std::mem::zeroed();
lodepng_decoder_settings_init(&mut settings);
settings
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum FilterStrategy {
LFS_ZERO = 0,
LFS_MINSUM,
LFS_ENTROPY,
LFS_BRUTE_FORCE,
LFS_PREDEFINED
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum AutoConvert {
LAC_NO = 0,
LAC_ALPHA,
LAC_AUTO,
LAC_AUTO_NO_NIBBLES,
LAC_AUTO_NO_PALETTE,
LAC_AUTO_NO_NIBBLES_NO_PALETTE
}
#[repr(C)]
pub struct EncoderSettings {
pub zlibsettings: CompressSettings,
pub auto_convert: AutoConvert,
pub filter_palette_zero: c_uint,
pub filter_strategy: FilterStrategy,
predefined_filters: *const u8,
pub force_palette: c_uint,
add_id: c_uint,
text_compression: c_uint,
}
impl EncoderSettings {
pub fn new() -> EncoderSettings {
unsafe {
let mut settings = ::std::mem::zeroed();
lodepng_encoder_settings_init(&mut settings);
settings
}
}
}
#[repr(C)]
pub struct State {
pub decoder: DecoderSettings,
pub encoder: EncoderSettings,
pub info_raw: ColorMode,
pub info_png: Info,
error: c_uint,
}
#[link(name="lodepng", kind="static")]
extern {
pub fn lodepng_decode_memory(out: &mut *mut u8, w: &mut c_uint, h: &mut c_uint, input: *const u8, insize: size_t, colortype: ColorType, bitdepth: c_uint) -> Error;
pub fn lodepng_encode_memory(out: &mut *mut u8, outsize: &mut size_t, image: *const u8, w: c_uint, h: c_uint, colortype: ColorType, bitdepth: c_uint) -> Error;
fn lodepng_error_text(code: c_uint) -> *const i8;
pub fn lodepng_compress_settings_init(settings: &mut CompressSettings);
pub fn lodepng_color_mode_init(info: &mut ColorMode);
pub fn lodepng_color_mode_cleanup(info: &mut ColorMode);
pub fn lodepng_color_mode_copy(dest: &mut ColorMode, source: &ColorMode) -> Error;
pub fn lodepng_palette_clear(info: &mut ColorMode);
pub fn lodepng_palette_add(info: &mut ColorMode, r: c_uchar, g: c_uchar, b: c_uchar, a: c_uchar) -> Error;
pub fn lodepng_get_bpp(info: &ColorMode) -> c_uint;
pub fn lodepng_get_channels(info: &ColorMode) -> c_uint;
pub fn lodepng_is_greyscale_type(info: &ColorMode) -> c_uint;
pub fn lodepng_is_alpha_type(info: &ColorMode) -> c_uint;
pub fn lodepng_is_palette_type(info: &ColorMode) -> c_uint;
pub fn lodepng_has_palette_alpha(info: &ColorMode) -> c_uint;
pub fn lodepng_can_have_alpha(info: &ColorMode) -> c_uint;
pub fn lodepng_get_raw_size(w: c_uint, h: c_uint, color: &ColorMode) -> size_t;
pub fn lodepng_info_init(info: &mut Info);
pub fn lodepng_info_cleanup(info: &mut Info);
pub fn lodepng_info_copy(dest: &mut Info, source: &Info) -> Error;
pub fn lodepng_clear_text(info: &mut Info);
pub fn lodepng_add_text(info: &mut Info, key: *const c_char, str: *const c_char) -> Error;
pub fn lodepng_clear_itext(info: &mut Info);
pub fn lodepng_add_itext(info: &mut Info, key: *const c_char, langtag: *const c_char, transkey: *const c_char, str: *const c_char) -> Error;
pub fn lodepng_convert(out: *mut u8, input: *const u8, mode_out: &mut ColorMode, mode_in: &ColorMode, w: c_uint, h: c_uint, fix_png: c_uint) -> Error;
pub fn lodepng_decoder_settings_init(settings: &mut DecoderSettings);
pub fn lodepng_auto_choose_color(mode_out: &mut ColorMode, image: *const u8, w: c_uint, h: c_uint, mode_in: &ColorMode, auto_convert: AutoConvert) -> Error;
pub fn lodepng_encoder_settings_init(settings: &mut EncoderSettings);
pub fn lodepng_state_init(state: &mut State);
pub fn lodepng_state_cleanup(state: &mut State);
pub fn lodepng_state_copy(dest: &mut State, source: &State);
pub fn lodepng_decode(out: &mut *mut u8, w: &mut c_uint, h: &mut c_uint, state: &mut State, input: *const u8, insize: size_t) -> Error;
pub fn lodepng_inspect(w: &mut c_uint, h: &mut c_uint, state: &mut State, input: *const u8, insize: size_t) -> Error;
pub fn lodepng_encode(out: &mut *mut u8, outsize: &mut size_t, image: *const u8, w: c_uint, h: c_uint, state: &mut State) -> Error;
pub fn lodepng_chunk_length(chunk: *const c_uchar) -> c_uint;
pub fn lodepng_chunk_type(chtype: [u8; 5], chunk: *const c_uchar);
pub fn lodepng_chunk_type_equals(chunk: *const c_uchar, chtype: *const u8) -> c_uchar;
pub fn lodepng_chunk_ancillary(chunk: *const c_uchar) -> c_uchar;
pub fn lodepng_chunk_private(chunk: *const c_uchar) -> c_uchar;
pub fn lodepng_chunk_safetocopy(chunk: *const c_uchar) -> c_uchar;
pub fn lodepng_chunk_data(chunk: *mut c_uchar) -> *mut c_uchar;
pub fn lodepng_chunk_check_crc(chunk: *const c_uchar) -> c_uint;
pub fn lodepng_chunk_generate_crc(chunk: *mut c_uchar);
pub fn lodepng_chunk_next(chunk: *mut c_uchar) -> *mut c_uchar;
pub fn lodepng_chunk_append(out: &mut *mut u8, outlength: *const size_t, chunk: *const c_uchar) -> Error;
pub fn lodepng_chunk_create(out: &mut *mut u8, outlength: *const size_t, length: c_uint, chtype: *const c_char, data: *const u8) -> Error;
pub fn lodepng_crc32(buf: *const u8, len: size_t) -> c_uint;
pub fn lodepng_zlib_compress(out: &mut *mut u8, outsize: &mut size_t, input: *const u8, insize: size_t, settings: &CompressSettings) -> Error;
pub fn lodepng_deflate(out: &mut *mut u8, outsize: &mut size_t, input: *const u8, insize: size_t, settings: &CompressSettings) -> Error;
}
impl Error {
pub fn to_result(self) -> Result<(), Error> {
match self {
Error(0) => Ok(()),
err => Err(err),
}
}
}
impl CompressSettings {
pub fn new() -> CompressSettings {
unsafe {
let mut settings = mem::zeroed();
lodepng_compress_settings_init(&mut settings);
return settings;
}
}
}
}
#[derive(Debug)]
pub struct Grey<ComponentType>(ComponentType);
#[derive(Debug)]
pub struct GreyAlpha<ComponentType>(ComponentType, ComponentType);
pub enum Image {
RawData(Bitmap<u8>),
Grey(Bitmap<Grey<u8>>),
Grey16(Bitmap<Grey<u16>>),
GreyAlpha(Bitmap<GreyAlpha<u8>>),
GreyAlpha16(Bitmap<GreyAlpha<u16>>),
RGBA(Bitmap<RGBA<u8>>),
RGB(Bitmap<RGB<u8>>),
RGBA16(Bitmap<RGBA<u16>>),
RGB16(Bitmap<RGB<u16>>),
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{} ({})", self.as_str(), self.0)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}", self.as_str())
}
}
#[allow(missing_copy_implementations)]
pub struct Chunk {
data: *mut c_uchar,
}
pub struct Bitmap<PixelType> {
pub buffer: CVec<PixelType>,
pub width: usize,
pub height: usize,
}
impl<T: Send> Bitmap<T> {
unsafe fn from_buffer(out: *mut u8, w: usize, h: usize) -> Bitmap<T>
where T: Send {
Bitmap::<T> {
buffer: cvec_with_free(mem::transmute(out), w * h),
width: w,
height: h,
}
}
}
impl<PixelType> fmt::Debug for Bitmap<PixelType> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{} × {} Bitmap}}", self.width, self.height)
}
}
fn required_size(w: usize, h: usize, colortype: ColorType, bitdepth: u32) -> usize {
colortype.to_color_mode(bitdepth).raw_size(w as c_uint, h as c_uint)
}
unsafe fn cvec_with_free<T>(ptr: *mut T, elts: usize) -> CVec<T>
where T: Send {
CVec::new_with_dtor(ptr, elts, |base: *mut T| {
free(base as *mut c_void);
})
}
unsafe fn new_bitmap(out: *mut u8, w: usize, h: usize, colortype: ColorType, bitdepth: c_uint) -> Image {
match (colortype, bitdepth) {
(LCT_RGBA, 8) =>Image::RGBA(Bitmap::from_buffer(out, w, h)),
(LCT_RGB, 8) => Image::RGB(Bitmap::from_buffer(out, w, h)),
(LCT_RGBA, 16) => Image::RGBA16(Bitmap::from_buffer(out, w, h)),
(LCT_RGB, 16) => Image::RGB16(Bitmap::from_buffer(out, w, h)),
(LCT_GREY, 8) => Image::Grey(Bitmap::from_buffer(out, w, h)),
(LCT_GREY, 16) => Image::Grey16(Bitmap::from_buffer(out, w, h)),
(LCT_GREY_ALPHA, 8) => Image::GreyAlpha(Bitmap::from_buffer(out, w, h)),
(LCT_GREY_ALPHA, 16) => Image::GreyAlpha16(Bitmap::from_buffer(out, w, h)),
(c,b) => Image::RawData(Bitmap {
buffer: cvec_with_free(out, required_size(w, h, c, b)),
width: w,
height: h,
}),
}
}
fn save_file<P: AsRef<Path>>(filepath: P, data: &[u8]) -> Result<(), Error> {
if let Ok(mut file) = File::create(filepath) {
if file.write_all(data).is_ok() {
return Ok(());
}
}
return Err(Error(79));
}
pub fn decode_memory(input: &[u8], colortype: ColorType, bitdepth: c_uint) -> Result<Image, Error> {
unsafe {
let mut out = mem::zeroed();
let mut w = 0;
let mut h = 0;
try!(ffi::lodepng_decode_memory(&mut out, &mut w, &mut h, input.as_ptr(), input.len() as size_t, colortype, bitdepth).to_result());
Ok(new_bitmap(out, w as usize, h as usize, colortype, bitdepth))
}
}
pub fn decode32(input: &[u8]) -> Result<Bitmap<RGBA<u8>>, Error> {
match try!(decode_memory(input, LCT_RGBA, 8)) {
Image::RGBA(img) => Ok(img),
_ => Err(Error(56)),
}
}
pub fn decode24(input: &[u8]) -> Result<Bitmap<RGB<u8>>, Error> {
match try!(decode_memory(input, LCT_RGB, 8)) {
Image::RGB(img) => Ok(img),
_ => Err(Error(56)),
}
}
pub fn decode_file<P: AsRef<Path>>(filepath: P, colortype: ColorType, bitdepth: c_uint) -> Result<Image, Error> {
if let Ok(mut file) = File::open(filepath) {
let mut data = Vec::new();
if file.read_to_end(&mut data).is_ok() {
return decode_memory(&data, colortype, bitdepth);
}
}
return Err(Error(78));
}
pub fn decode32_file<P: AsRef<Path>>(filepath: P) -> Result<Bitmap<RGBA<u8>>, Error> {
match try!(decode_file(filepath, LCT_RGBA, 8)) {
Image::RGBA(img) => Ok(img),
_ => Err(Error(56)),
}
}
pub fn decode24_file<P: AsRef<Path>>(filepath: P) -> Result<Bitmap<RGB<u8>>, Error> {
match try!(decode_file(filepath, LCT_RGB, 8)) {
Image::RGB(img) => Ok(img),
_ => Err(Error(56)),
}
}
fn with_buffer_for_type<PixelType, F>(image: &[PixelType], w: usize, h: usize, colortype: ColorType, bitdepth: u32, mut f: F) -> Error
where F: FnMut(*const u8) -> Error
{
if image.len() * mem::size_of::<PixelType>() != required_size(w, h, colortype, bitdepth) {
return Error(84);
}
f(unsafe {mem::transmute(image.as_ptr())})
}
pub fn encode_memory<PixelType>(image: &[PixelType], w: usize, h: usize, colortype: ColorType, bitdepth: c_uint) -> Result<CVec<u8>, Error> {
unsafe {
let mut out = mem::zeroed();
let mut outsize = 0;
try!(with_buffer_for_type(image, w, h, colortype, bitdepth, |ptr| {
ffi::lodepng_encode_memory(&mut out, &mut outsize, ptr, w as c_uint, h as c_uint, colortype, bitdepth)
}).to_result());
Ok(cvec_with_free(out, outsize as usize))
}
}
pub fn encode32<PixelType>(image: &[PixelType], w: usize, h: usize) -> Result<CVec<u8>, Error> {
encode_memory(image, w, h, LCT_RGBA, 8)
}
pub fn encode24<PixelType>(image: &[PixelType], w: usize, h: usize) -> Result<CVec<u8>, Error> {
encode_memory(image, w, h, LCT_RGB, 8)
}
pub fn encode_file<PixelType, P: AsRef<Path>>(filepath: P, image: &[PixelType], w: usize, h: usize, colortype: ColorType, bitdepth: c_uint) -> Result<(), Error> {
let encoded = try!(encode_memory(image, w, h, colortype, bitdepth));
save_file(filepath, encoded.as_cslice().as_ref())
}
pub fn encode32_file<PixelType, P: AsRef<Path>>(filepath: P, image: &[PixelType], w: usize, h: usize) -> Result<(), Error> {
encode_file(filepath, image, w, h, LCT_RGBA, 8)
}
pub fn encode24_file<PixelType, P: AsRef<Path>>(filepath: P, image: &[PixelType], w: usize, h: usize) -> Result<(), Error> {
encode_file(filepath, image, w, h, LCT_RGB, 8)
}
pub fn convert<PixelType>(input: &[PixelType], mode_out: &mut ColorMode, mode_in: &ColorMode, w: usize, h: usize, fix_png: bool) -> Result<Image, Error> {
unsafe {
let out = mem::zeroed();
try!(with_buffer_for_type(input, w, h, mode_in.colortype(), mode_in.bitdepth(), |ptr| {
ffi::lodepng_convert(out, ptr, &mut mode_out.data, &mode_in.data, w as c_uint, h as c_uint, fix_png as c_uint)
}).to_result());
Ok(new_bitmap(out, w, h, mode_out.colortype(), mode_out.bitdepth()))
}
}
pub fn auto_choose_color(mode_out: &mut ColorMode, image: *const u8, w: usize, h: usize, mode_in: &ColorMode, auto_convert: AutoConvert) -> Result<(), Error> {
unsafe {
ffi::lodepng_auto_choose_color(&mut mode_out.data, image, w as c_uint, h as c_uint, &mode_in.data, auto_convert).to_result()
}
}
impl Chunk {
pub fn len(&self) -> usize {
unsafe {
ffi::lodepng_chunk_length(&*self.data) as usize
}
}
pub fn is_ancillary(&self) -> c_uchar {
unsafe {
ffi::lodepng_chunk_ancillary(&*self.data)
}
}
pub fn is_private(&self) -> bool {
unsafe {
ffi::lodepng_chunk_private(&*self.data) != 0
}
}
pub fn is_safetocopy(&self) -> bool {
unsafe {
ffi::lodepng_chunk_safetocopy(&*self.data) != 0
}
}
pub fn data(&self) -> *mut c_uchar {
unsafe {
ffi::lodepng_chunk_data(self.data)
}
}
pub fn check_crc(&self) -> bool {
unsafe {
ffi::lodepng_chunk_check_crc(&*self.data) != 0
}
}
pub fn generate_crc(&mut self) {
unsafe {
ffi::lodepng_chunk_generate_crc(self.data)
}
}
pub fn next(&self) -> Option<Chunk> {
unsafe {
match ffi::lodepng_chunk_next(self.data) {
ptr if !ptr.is_null() => Some(Chunk {data: ptr}),
_ => None,
}
}
}
pub fn append(&self, out: &mut *mut u8, outlength: *const size_t) -> Result<(), Error> {
unsafe {
ffi::lodepng_chunk_append(out, outlength, &*self.data).to_result()
}
}
pub fn create(out: &mut *mut u8, outlength: *const size_t, length: c_uint, chtype: *const c_char, data: *const u8) -> Result<(), Error> {
unsafe {
ffi::lodepng_chunk_create(out, outlength, length, chtype, data).to_result()
}
}
}
pub fn zlib_compress(input: &[u8], settings: &CompressSettings) -> Result<CVec<u8>, Error> {
unsafe {
let mut out = mem::zeroed();
let mut outsize = 0;
try!(ffi::lodepng_zlib_compress(&mut out, &mut outsize, input.as_ptr(), input.len() as size_t, settings).to_result());
Ok(cvec_with_free(out, outsize as usize))
}
}
pub fn deflate(input: &[u8], settings: &CompressSettings) -> Result<CVec<u8>, Error> {
unsafe {
let mut out = mem::zeroed();
let mut outsize = 0;
try!(ffi::lodepng_deflate(&mut out, &mut outsize, input.as_ptr(), input.len() as size_t, settings).to_result());
Ok(cvec_with_free(out, outsize as usize))
}
}
#[cfg(test)]
mod test {
use std::mem;
use super::*;
#[test]
fn pixel_sizes() {
assert_eq!(4, mem::size_of::<RGBA<u8>>());
assert_eq!(3, mem::size_of::<RGB<u8>>());
assert_eq!(2, mem::size_of::<GreyAlpha<u8>>());
assert_eq!(1, mem::size_of::<Grey<u8>>());
}
#[test]
fn create_and_dstroy1() {
DecoderSettings::new();
EncoderSettings::new();
CompressSettings::new();
}
#[test]
fn create_and_dstroy2() {
ColorMode::new().clone();
Info::new().clone();
State::new().clone().info_raw();
}
}