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
#![crate_name = "freeimage"]
#![crate_type = "lib"]
#![allow(non_camel_case_types,dead_code,non_snake_case,non_upper_case_globals)]

extern crate libc;
#[macro_use] extern crate enum_primitive;
extern crate num;


use std::slice;
use std::mem;
use std::ptr;
use std::ffi::CString;
use num::FromPrimitive;

// re-export constants
pub use consts::*;
pub mod ffi;
pub mod consts;

pub struct Bitmap {
    ptr: *const ffi::FIBITMAP,
}

unsafe impl Send for Bitmap{}

impl Clone for Bitmap{
    fn clone(&self) -> Bitmap{
        Bitmap{ ptr: unsafe{ ffi::FreeImage_Clone(self.ptr) } }
    }
}

enum_from_primitive! {
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Type{
    UNKNOWN = 0,
    BITMAP = 1,
    UINT16 = 2,
    INT16 = 3,
    UINT32 = 4,
    INT32 = 5,
    FLOAT = 6,
    DOUBLE = 7,
    COMPLEX = 8,
    RGB16 = 9,
    RGBA16 = 10,
    RGBF = 11,
    RGBAF = 12,
}
}


enum_from_primitive! {
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Filter{
    BOX = 0,
    BILINEAR = 1,
    BSPLINE = 2,
    BICUBIC = 3,
    CATMULLROM = 4,
    LANCZOS3 = 5,
}
}

impl Drop for Bitmap {

	fn drop( &mut self ) {
		unsafe { ffi::FreeImage_Unload( self.ptr ); }
	}
}

pub fn init() {
	unsafe { ffi::FreeImage_Initialise( 0 ) }
}

unsafe fn file_type(filename: &str) -> Format {
	ffi::FreeImage_GetFileType( CString::new(filename.as_bytes()).unwrap().as_ptr(), 0 )
}

unsafe fn file_type_from_name(filename: &str) -> Format {
    ffi::FreeImage_GetFIFFromFilename(CString::new(filename.as_bytes()).unwrap().as_ptr())
}

pub fn supports_reading(fif: Format) -> bool {
	unsafe {
		1 == ffi::FreeImage_FIFSupportsReading( fif )
	}
}

pub fn supports_writting(fif: Format) -> bool{
    unsafe{
        1 == ffi::FreeImage_FIFSupportsWriting( fif )
    }
}

impl Bitmap {
	pub fn load(filename: &str) -> Result<Bitmap,&'static str> {
		unsafe {
            let cname = CString::new(filename.as_bytes()).unwrap();
            let fif = ffi::FreeImage_GetFIFFromFilename(cname.as_ptr());
			let ptr = ffi::FreeImage_Load(fif, cname.as_ptr(), 0);
			if ptr.is_null(){
			    Err( "FreeImage_Load returned null" )
			}else{
				Ok(Bitmap { ptr: mem::transmute(ptr) })
			}
		}
	}

	pub fn load_with_format(fif: Format, filename: &str) -> Result<Bitmap,&'static str> {
		unsafe {
			let ptr = ffi::FreeImage_Load( fif, CString::new(filename.as_bytes()).unwrap().as_ptr(), 0 );
			if ptr.is_null(){
			    Err( "FreeImage_Load returned null" )
			}else{
				Ok(Bitmap { ptr: mem::transmute(ptr) })
			}
		}
	}

    pub fn load_from_memory(buffer: Vec<u8>) -> Result<Bitmap,&'static str> {
		unsafe {
            let hmem = ffi::FreeImage_OpenMemory( mem::transmute(buffer.as_ptr()), buffer.len() as u32 );
            if hmem.is_null(){
                Err( "FreeImage_OpenMemory returned null" )
            }else{
                let fif = ffi::FreeImage_GetFileTypeFromMemory(mem::transmute(hmem), 0);
                if fif!=Format::UNKNOWN{
                    let ptr = ffi::FreeImage_LoadFromMemory(fif,mem::transmute(hmem),0);
                    if ptr.is_null(){
                        Err( "FreeImage_LoadFromMemory returned null" )
                    }else{
						Ok(Bitmap { ptr: mem::transmute(ptr) })
                    }
                }else{
                    Err( "FreeImage_GetFileTypeFromMemory returned UNKOWN" )
                }
            }
		}
    }

    pub fn new<T: Clone>(ty: Type, width: usize, height: usize, bpp: usize, data: Option<&[T]>) -> Bitmap{
        unsafe{
            let ptr = ffi::FreeImage_AllocateT(ty as i32, width as i32, height as i32, bpp as i32, 0, 0, 0);
            let mut bitmap = Bitmap{ ptr: ptr };
            if let Some(data) = data{
                let bytes_per_channel = mem::size_of::<T>();
                let bytes_pp =  bpp / 8;
                let channels = bytes_pp / bytes_per_channel;
                if bitmap.pitch() != width * bytes_pp{
                    for (line_src, line_dst) in data.chunks(width * channels).zip(bitmap.scanlines_mut()){
                        ptr::copy(line_src.as_ptr(), mem::transmute(line_dst.as_mut_ptr()), line_src.len() * bytes_per_channel);
                    }
                }else{
                    bitmap.pixels_mut().clone_from_slice(data);
                }
            }
            bitmap
        }
    }

	pub fn save(&self, filename: &str, flags: i32) -> Result<(),String>{
	    unsafe{
	        let format = file_type_from_name(filename);
	        if supports_writting(format){
				ffi::FreeImage_Save(format, self.ptr, CString::new(filename.as_bytes()).unwrap().as_ptr(),flags);
                Ok(())
	        }else{
                Err(format!("Format {:?} doesn't support writing", format))
            }
	    }
	}

	pub fn width(&self) -> usize {
		unsafe { ffi::FreeImage_GetWidth( self.ptr ) as usize }
	}


	pub fn height(&self) -> usize {
		unsafe { ffi::FreeImage_GetHeight( self.ptr ) as usize }
	}


	pub fn bpp(&self) -> usize {
		unsafe { ffi::FreeImage_GetBPP( self.ptr ) as usize }
	}

    pub fn ty(&self) -> Type{
        unsafe{ Type::from_i32(ffi::FreeImage_GetImageType( self.ptr )).unwrap() }
    }


	pub fn pitch(&self) -> usize {
		unsafe { ffi::FreeImage_GetPitch( self.ptr ) as usize }
	}


	fn bits_unsafe(&self) -> *const u8 {
		unsafe { ffi::FreeImage_GetBits( self.ptr ) }
	}

	fn bits_unsafe_mut(&mut self) -> *mut u8 {
		unsafe { ffi::FreeImage_GetBits( self.ptr ) as *mut u8}
	}


	unsafe fn scanline_unsafe(&self, scanline: usize) -> *const u8 {
		ffi::FreeImage_GetScanLine( self.ptr, scanline as libc::c_int ) as *const u8
	}

	unsafe fn scanline_unsafe_mut(&self, scanline: usize) -> *mut u8 {
		ffi::FreeImage_GetScanLine( self.ptr, scanline as libc::c_int ) as *mut u8
	}

	pub fn bits(&self) -> &[u8] {
		let pitch = self.pitch();
		let height = self.height();

		unsafe{ slice::from_raw_parts( self.bits_unsafe(), pitch * height) }
	}

	pub fn pixels<T>(&self) -> &[T] {
		let pitch = self.pitch();
		let height = self.height();

		unsafe{ slice::from_raw_parts( mem::transmute(self.bits_unsafe()), pitch / mem::size_of::<T>() * height) }
	}

	pub fn bits_mut(&mut self) -> &mut [u8] {
		let pitch = self.pitch();
		let height = self.height();

		unsafe{ slice::from_raw_parts_mut( self.bits_unsafe_mut(), pitch * height) }
	}

	pub fn pixels_mut<T>(&mut self) -> &mut [T] {
		let pitch = self.pitch();
		let height = self.height();

		unsafe{ slice::from_raw_parts_mut( mem::transmute(self.bits_unsafe_mut()), pitch / mem::size_of::<T>() * height) }
	}

	pub fn scanlines<'a>(&'a self) -> ScanLines<'a>{
	    ScanLines{ bitmap: self, line: 0 }
	}

	pub fn scanlines_mut(&mut self) -> ScanLinesMut{
	    ScanLinesMut{ bitmap: self, line: 0 }
	}

    pub fn flip_vertical(self) -> Result<Bitmap,String>{
        unsafe{
            if ffi::FreeImage_FlipVertical(self.ptr) == 0{
                Err("Couldn't flip vertically".to_string())
            }else{
                Ok(self)
            }
        }
    }

    pub fn rescale(&self, w: usize, h: usize, filter: Filter) -> Result<Bitmap, String>{
        unsafe{
            let scaled_ptr = ffi::FreeImage_Rescale(self.ptr, w as i32, h as i32, filter as ffi::FREE_IMAGE_FILTER);
            if scaled_ptr == ptr::null(){
                Err("Couldn't scale image".to_string())
            }else{
                Ok(Bitmap{ptr: scaled_ptr})
            }
        }
    }
}

pub struct ScanLines<'a>{
    bitmap: &'a Bitmap,
    line: usize
}

impl<'a> Iterator for ScanLines<'a>{
    type Item = &'a [u8];
    fn next(&mut self) -> Option<&'a [u8]>{
		let pitch = self.bitmap.pitch();
		let height = self.bitmap.height();

		if self.line == height {
			None
		} else {
			let bits = unsafe { self.bitmap.scanline_unsafe(self.line) };

			if bits.is_null() {
				None
			} else {
			    self.line += 1;
				unsafe{ Some(slice::from_raw_parts( bits, pitch )) }
			}
		}
    }
}


pub struct ScanLinesMut<'a>{
    bitmap: &'a mut Bitmap,
    line: usize
}

impl<'a> Iterator for ScanLinesMut<'a>{
    type Item = &'a mut [u8];
    fn next(&mut self) -> Option<&'a mut [u8]>{
		let pitch = self.bitmap.pitch();
		let height = self.bitmap.height();

		if self.line == height {
			None
		} else {
			let bits = unsafe { self.bitmap.scanline_unsafe_mut(self.line) };

			if bits.is_null() {
				None
			} else {
			    self.line += 1;
				unsafe{ Some(slice::from_raw_parts_mut( bits, pitch )) }
			}
		}
    }
}