1    def write (path : String
2               width : u32
3               height : u32
4               bpp : u32
5               bytes : Slice<u8>) =
6        let format = case bpp of
7            32 -> Format/Rgba
8            8 -> Format/Gray
9            else -> fail
10   
11       let mut image = Image
12           version = Png.image_version
13           =width
14           =height
15           =format
16           f@ Image.default
17   
18       let c_path @owner = path.to_c_string
19       let result = Png.write_to_file image@mut_ptr
20                                      c_path 0 bytes.ptr 0 null
21       if result == 0 then
22           fail "cannot write png file"
23   
24   def read (path : String) : (u32, u32, u32, Array<u8>) =
25       let mut image = Image
26           version = Png.image_version
27           f@ Image.default
28   
29       let c_path @owner = path.to_c_string
30       let result = Png.begin_read_from_file image@mut_ptr
31                                             c_path
32       if result == 0 then
33           fail "cannot read png file"
34       else
35           let bytes_per_pixel = case image.format of
36               Format/Gray -> 1
37               Format/Rgba -> 4
38               else -> fail
39   
40           let size = image.width * image.height * bytes_per_pixel
41           let buffer = Array<u8> size
42   
43           let finish_result = Png.finish_read image@mut_ptr null buffer.as_mut_ptr
44                                               0 null
45           if finish_result == 0 then
46               fail "cannot read png file"
47   
48           (image.width, image.height, bytes_per_pixel * 8, buffer)
49