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
//! Image loading and handling.
use bitflags::bitflags;
use core::{fmt, ops, ptr, slice};
use std::{ffi::CString, path::Path};
use ffi::{self, BLImageCore};
use crate::{
array::Array,
codec::ImageCodec,
error::{errcode_to_result, expect_mem_err, Result},
geometry::{SizeD, SizeI},
variant::WrappedBlCore,
};
use ffi::BLFormat::*;
bl_enum! {
/// Pixel format.
pub enum ImageFormat {
/// 32-bit premultiplied ARGB pixel format (8-bit components).
PRgb32 = BL_FORMAT_PRGB32,
/// 32-bit (X)RGB pixel format (8-bit components, alpha ignored).
XRgb32 = BL_FORMAT_XRGB32,
/// 8-bit alpha-only pixel format.
A8 = BL_FORMAT_A8,
}
Default => PRgb32
}
use ffi::BLFormatFlags;
bitflags! {
/// Pixel format flags.
pub struct FormatFlags: u32 {
/// Pixel format provides RGB components.
const RGB = BLFormatFlags::BL_FORMAT_FLAG_RGB as u32;
/// Pixel format provides only alpha component.
const ALPHA = BLFormatFlags::BL_FORMAT_FLAG_ALPHA as u32;
/// A combination of RGB | ALPHA.
const RGBA = BLFormatFlags::BL_FORMAT_FLAG_RGBA as u32;
/// Pixel format provides LUM component (and not RGB components).
const LUM = BLFormatFlags::BL_FORMAT_FLAG_LUM as u32;
/// A combination of BL_FORMAT_FLAG_LUM | BL_FORMAT_FLAG_ALPHA.
const LUMA = BLFormatFlags::BL_FORMAT_FLAG_LUMA as u32;
/// Indexed pixel format the requres a palette (I/O only).
const INDEXED = BLFormatFlags::BL_FORMAT_FLAG_INDEXED as u32;
/// RGB components are premultiplied by alpha component.
const PREMULTIPLIED = BLFormatFlags::BL_FORMAT_FLAG_PREMULTIPLIED as u32;
/// Pixel format doesn't use native byte-order (I/O only).
const BYTE_SWAP = BLFormatFlags::BL_FORMAT_FLAG_BYTE_SWAP as u32;
/// Pixel components are byte aligned (all 8bpp).
const BYTE_ALIGNED = BLFormatFlags::BL_FORMAT_FLAG_BYTE_ALIGNED as u32;
}
}
use ffi::BLImageInfoFlags::*;
bitflags! {
/// Flags used by [`ImageInfo`].
pub struct ImageInfoFlags: u32 {
/// rogressive mode.
const PROGRESSIVE = BL_IMAGE_INFO_FLAG_PROGRESSIVE as u32;
}
}
use ffi::BLImageScaleFilter::*;
bl_enum! {
/// Filter type used by [`Image::scale`].
///
/// [`Image::scale`]: struct.Image.html#method.scale
pub enum ImageScaleFilter {
/// Nearest neighbor filter (radius 1.0).
Nearest = BL_IMAGE_SCALE_FILTER_NEAREST,
/// Bilinear filter (radius 1.0).
Bilinear = BL_IMAGE_SCALE_FILTER_BILINEAR,
/// Bicubic filter (radius 2.0).
Bicubic = BL_IMAGE_SCALE_FILTER_BICUBIC,
/// Bell filter (radius 1.5).
Bell = BL_IMAGE_SCALE_FILTER_BELL,
/// Gauss filter (radius 2.0).
Gauss = BL_IMAGE_SCALE_FILTER_GAUSS,
/// Hermite filter (radius 1.0).
Hermite = BL_IMAGE_SCALE_FILTER_HERMITE,
/// Hanning filter (radius 1.0).
Hanning = BL_IMAGE_SCALE_FILTER_HANNING,
/// Catrom filter (radius 2.0).
Catrom = BL_IMAGE_SCALE_FILTER_CATROM,
/// Bessel filter (radius 3.2383).
Bessel = BL_IMAGE_SCALE_FILTER_BESSEL,
/// Sinc filter (radius 2.0, adjustable through [`ImageScaleOptions`]).
Sinc = BL_IMAGE_SCALE_FILTER_SINC,
/// Blackman filter (radius 2.0, adjustable through [`ImageScaleOptions`]).
Lanczos = BL_IMAGE_SCALE_FILTER_LANCZOS,
/// Lanczos filter (radius 2.0, adjustable through [`ImageScaleOptions`]).
Blackman = BL_IMAGE_SCALE_FILTER_BLACKMAN,
/// Mitchell filter (radius 2.0, parameters 'b' and 'c' passed through [`ImageScaleOptions`]).
Mitchell = BL_IMAGE_SCALE_FILTER_MITCHELL,
/// Filter using a user-function, must be passed through BLImageScaleOptions.
User = BL_IMAGE_SCALE_FILTER_USER,
}
Default => Nearest
}
// FIXME merge this and ImageScaleFilter into an algebraic data type
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct ImageScaleOptions {
user_func: ffi::BLImageScaleUserFunc,
user_data: *mut std::os::raw::c_void,
pub radius: f64,
pub b: f64,
pub c: f64,
_data: f64,
}
impl Default for ImageScaleOptions {
fn default() -> Self {
ImageScaleOptions {
user_func: None,
user_data: ptr::null_mut(),
radius: 2.0,
b: 1.0 / 3.0,
c: 1.0 / 3.0,
_data: 0.0,
}
}
}
/// A 2D raster image.
#[repr(transparent)]
pub struct Image {
core: BLImageCore,
}
unsafe impl WrappedBlCore for Image {
type Core = ffi::BLImageCore;
const IMPL_TYPE_INDEX: usize = crate::variant::ImplType::Image as usize;
#[inline]
fn from_core(core: Self::Core) -> Image {
Image { core }
}
}
impl Image {
/// Creates a new empty image with the specified dimensions and image format.
#[inline]
pub fn new(width: i32, height: i32, format: ImageFormat) -> Result<Image> {
unsafe {
let mut this = Image::from_core(*Self::none());
errcode_to_result(ffi::blImageCreate(
this.core_mut(),
width,
height,
format.into(),
))
.map(|_| this)
}
}
/* FIXME figure out a solution for the lifetime issue
#[inline]
pub fn new_external(
width: i32,
height: i32,
format: ImageFormat,
data: &'a mut [u8],
stride: isize,
) -> Result<Image<'a>> {
unsafe {
let mut this = Image::from_core(*Self::none());
errcode_to_result(ffi::blImageCreateFromData(
this.core_mut(),
width,
height,
format.into(),
data.as_mut_ptr() as *mut _,
stride,
None,
ptr::null_mut(),
))
.map(|_| this)
}
}*/
/// Attempts to create a new image with the specified dimensions and image format by decoding
/// the data with the given codec.
pub fn from_data<R: AsRef<[u8]>>(
width: i32,
height: i32,
format: ImageFormat,
data: &R,
codecs: &Array<ImageCodec>,
) -> Result<Image> {
let mut this = Self::new(width, height, format)?;
unsafe {
errcode_to_result(ffi::blImageReadFromData(
this.core_mut(),
data.as_ref().as_ptr() as *const _,
data.as_ref().len(),
codecs.core(),
))
.map(|_| this)
}
}
pub fn from_path<P: AsRef<Path>>(path: P, codecs: &Array<ImageCodec>) -> Result<Image> {
let mut this = Image::from_core(*Self::none());
let path = CString::new(path.as_ref().to_string_lossy().into_owned().into_bytes()).unwrap();
unsafe {
errcode_to_result(ffi::blImageReadFromFile(
this.core_mut(),
path.as_ptr(),
codecs.core(),
))
.map(|_| this)
}
}
/// This image's format.
#[inline]
pub fn format(&self) -> ImageFormat {
(self.impl_().format as u32).into()
}
/// This image's dimensions.
#[inline]
pub fn size(&self) -> SizeI {
let ffi::BLSizeI { w, h } = self.impl_().size;
SizeI { w, h }
}
/// This image's width.
#[inline]
pub fn width(&self) -> i32 {
self.size().w
}
/// This image's height.
#[inline]
pub fn height(&self) -> i32 {
self.size().h
}
/// Returns an [`ImageData`] instance containing most of this image's information.
pub fn data(&self) -> ImageData<'_> {
unsafe {
let mut data = std::mem::zeroed();
ffi::blImageGetData(self.core(), &mut data);
let ffi::BLSizeI { w, h } = data.size;
ImageData {
data: slice::from_raw_parts(
data.pixelData as *mut _,
(h as isize * data.stride) as usize,
),
stride: data.stride as isize / w as isize,
size: (w, h),
format: data.format.into(),
flags: ImageInfoFlags::from_bits_truncate(data.flags),
}
}
}
#[inline]
pub fn scale(
&mut self,
size: SizeI,
filter: ImageScaleFilter,
options: Option<&ImageScaleOptions>,
) -> Result<()> {
unsafe {
errcode_to_result(ffi::blImageScale(
self.core_mut(),
self.core(),
&size as *const _ as *const _,
filter as u32,
options.map_or(ptr::null(), |opt| opt as *const _ as *const _),
))
}
}
/// Writes the image to the file at the given path.
pub fn write_to_file<P: AsRef<Path>>(&self, path: P, codec: &ImageCodec) -> Result<()> {
unsafe {
let path =
CString::new(path.as_ref().to_string_lossy().as_bytes()).expect("Invalid Path");
errcode_to_result(ffi::blImageWriteToFile(
self.core(),
path.as_ptr(),
codec.core(),
))
}
}
/// Writes the image to the given [`Array`].
#[inline]
pub fn write_to_data(&self, dst: &mut Array<u8>, codec: &ImageCodec) -> Result<()> {
unsafe {
errcode_to_result(ffi::blImageWriteToData(
self.core(),
dst.core_mut(),
codec.core(),
))
}
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Image")
.field("size", &self.size())
.field("format", &self.format())
.finish()
}
}
impl ops::Deref for Image {
type Target = [u8];
fn deref(&self) -> &Self::Target {
unsafe {
let mut data = std::mem::zeroed();
expect_mem_err(ffi::blImageGetData(self.core(), &mut data));
slice::from_raw_parts(
data.pixelData as *const _,
(data.size.h as isize * data.stride) as usize,
)
}
}
}
impl ops::DerefMut for Image {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
let mut data = std::mem::zeroed();
expect_mem_err(ffi::blImageMakeMutable(self.core_mut(), &mut data));
slice::from_raw_parts_mut(
data.pixelData as *mut _,
(data.size.h as isize * data.stride) as usize,
)
}
}
}
impl AsRef<[u8]> for Image {
fn as_ref(&self) -> &[u8] {
self
}
}
impl AsMut<[u8]> for Image {
fn as_mut(&mut self) -> &mut [u8] {
self
}
}
impl PartialEq for Image {
#[inline]
fn eq(&self, other: &Self) -> bool {
unsafe { ffi::blImageEquals(self.core(), other.core()) }
}
}
impl Clone for Image {
#[inline]
fn clone(&self) -> Image {
Self::from_core(self.init_weak())
}
}
impl Drop for Image {
fn drop(&mut self) {
unsafe { ffi::blImageReset(&mut self.core) };
}
}
/// A struct containing information about an image.
#[derive(Debug)]
pub struct ImageData<'a> {
pub data: &'a [u8],
pub stride: isize,
pub size: (i32, i32),
pub format: ImageFormat,
pub flags: ImageInfoFlags,
}
/// Image information provided by image codecs.
#[derive(Debug)]
pub struct ImageInfo {
/// Image size.
pub size: SizeI,
/// Pixel density per one meter, can contain fractions.
pub density: SizeD,
/// Image flags.
pub flags: ImageInfoFlags,
/// Image depth.
pub depth: u16,
/// Number of planes.
pub plane_count: u16,
/// Number of frames (0 = unknown/unspecified).
pub frame_count: u64,
/// Image format (as understood by codec).
format: [u8; 16],
/// Image compression (as understood by codec).
compression: [u8; 16],
}
#[cfg(test)]
mod test_codec {
use crate::{geometry::SizeI, image::Image};
#[test]
fn test_image_err_on_zero_size() {
assert!(Image::new(0, 100, Default::default()).is_err());
assert!(Image::new(100, 0, Default::default()).is_err());
assert!(Image::new(0, 0, Default::default()).is_err());
}
#[test]
fn test_image_scale() {
let new_size = SizeI { w: 100, h: 100 };
let mut image = Image::new(50, 50, Default::default()).unwrap();
image.scale(new_size, Default::default(), None).unwrap();
assert_eq!(image.size(), new_size);
}
#[test]
fn test_image_data() {
let image = Image::new(50, 50, Default::default()).unwrap();
let image_data = image.data();
assert_eq!(image_data.stride, 4);
assert_eq!(
image_data.data.to_vec().len() as isize,
50 * 50 * image_data.stride
);
}
}