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
use nalgebra::SMatrix;
use std::fmt::Display;
use xege_ffi::*;
use crate::{DrawableDevice, GraphicsEnvironment, ImageDraw};
#[derive(Debug, thiserror::Error)]
pub enum ImageError {
#[error("Memory allocation failed during read operation.")]
AllocError,
#[error("The file does not exist.")]
FileNotFound,
#[error("Pointer conversion failed.")]
NullPointer,
#[error("Reading failed.")]
IOError,
#[error("Other Unknown error.")]
UnknownError,
#[error("Path parsing error.")]
PathParserError,
}
/// Image
#[derive(Debug)]
pub struct Image {
ptr: *mut ege_IMAGE,
}
impl Display for Image {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Image({:p})", self.ptr)
}
}
impl DrawableDevice for Image {
fn const_ptr(&self) -> *const ege_IMAGE {
self.ptr as *const _
}
fn mut_ptr(&mut self) -> *mut ege_IMAGE {
self.ptr
}
}
impl Drop for Image {
fn drop(&mut self) {
unsafe { ege_delimage(self.ptr) };
}
}
impl Image {
/// Create a new image.
///
/// # Parameters
/// - `width`: The width of the image.
/// - `height`: The height of the image.
///
/// # Returns
/// A new `Image` object.
pub fn new(width: u32, height: u32) -> Self {
Self {
ptr: unsafe { ege_newimage1(width.max(1) as _, height.max(1) as _) },
}
}
pub(crate) fn handle_result(result: i32) -> Result<(), ImageError> {
match result {
xege_ffi::ege_graphics_errors_grOk => Ok(()),
xege_ffi::ege_graphics_errors_grFileNotFound => Err(ImageError::FileNotFound),
xege_ffi::ege_graphics_errors_grAllocError => Err(ImageError::AllocError),
xege_ffi::ege_graphics_errors_grNullPointer => Err(ImageError::NullPointer),
xege_ffi::ege_graphics_errors_grIOerror => Err(ImageError::IOError),
_ => Err(ImageError::UnknownError),
}
}
/// Load an image from a file.
///
/// # Parameters
/// - `filename`: The filename of the image.
///
/// # Returns
/// A new `Image` object. Or an error.
pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ImageError> {
let ptr = unsafe { ege_newimage() };
let path = path
.as_ref()
.to_str()
.map_or_else(|| Err(ImageError::PathParserError), |s| Ok(s))?
.encode_utf16()
.chain(Some(0))
.collect::<Vec<u16>>();
let result = unsafe { ege_getimage3(ptr, path.as_ptr(), 0, 0) };
Self::handle_result(result).map(|_| Self { ptr })
}
/// Load an image from a window.
///
/// # Parameters
/// - `x`: The x position of the window.
/// - `y`: The y position of the window.
/// - `width`: The width of the window.
/// - `height`: The height of the window.
///
/// # Returns
/// A new `Image` object. Or an error.
pub fn from_window(x: i32, y: i32, width: i32, height: i32) -> Result<Self, ImageError> {
let ptr = unsafe { ege_newimage() };
let result = unsafe { ege_getimage(ptr, x, y, width, height) };
Self::handle_result(result).map(|_| Self { ptr })
}
/// Load an image from another image.
///
/// # Parameters
/// - `image`: The source image.
/// - `x`: The x position of the source image.
/// - `y`: The y position of the source image.
/// - `width`: The width of the source image.
/// - `height`: The height of the source image.
///
/// # Returns
/// A new `Image` object. Or an error.
pub fn from_image(
image: &Image,
x: i32,
y: i32,
width: i32,
height: i32,
) -> Result<Self, ImageError> {
let ptr = unsafe { ege_newimage() };
let result = unsafe { ege_getimage1(ptr, image.ptr, x, y, width, height) };
Self::handle_result(result).map(|_| Self { ptr })
}
/// Save an image to a file.
///
/// # Parameters
/// - `filename`: The filename of the image.
/// - `with_alpha`: Whether to save the alpha channel.
///
/// # Note
/// It only supports BMP and PNG formats.
pub fn save<P: AsRef<std::path::Path>>(
&self,
path: P,
with_alpha: bool,
) -> Result<(), ImageError> {
let path = path
.as_ref()
.to_str()
.map_or_else(|| Err(ImageError::PathParserError), |s| Ok(s))?
.encode_utf16()
.chain(Some(0))
.collect::<Vec<u16>>();
let result = unsafe { ege_saveimage1(self.ptr, path.as_ptr(), with_alpha) };
Self::handle_result(result)
}
}
impl Image {
/// Resize the image.
///
/// # Parameters
/// - `width`: The new width of the image.
/// - `height`: The new height of the image.
pub fn resize(&mut self, width: i32, height: i32) -> Result<(), ImageError> {
let result = unsafe { ege_resize(self.ptr, width, height) };
Self::handle_result(result)
}
/// Resize the image.
///
/// # Parameters
/// - `width`: The new width of the image.
/// - `height`: The new height of the image.
pub unsafe fn resize_f(&mut self, width: i32, height: i32) -> Result<(), ImageError> {
let result = unsafe { ege_resize_f(self.ptr, width, height) };
Self::handle_result(result)
}
}
impl Clone for Image {
fn clone(&self) -> Self {
let mut img = Image::new(self.getwidth(), self.getheight());
img.drawimage(self, 0, 0);
img
}
}
use crate::ARGB;
/// Edge pixel processing mode.
///
/// It is used to describe the handling method when
/// the template element position does not match the pixel.
pub enum TemplateMode {
/// Treat non-existent pixels as white(0xFFFFFF).
White,
/// Treat non-existent pixels as black(0x000000).
Black,
/// Ignore non-existent pixels.
Ignore,
/// Ignore pixel regions that cannot be perfectly matched by the template.
DotCare,
}
/// Mask channels to apply.
#[bitmask_enum::bitmask]
pub enum ApplyMask {
Red,
Blue,
Green,
All = 15,
}
impl Image {
/// Apply a transformation to the image.
///
/// # Parameters
/// - `trans`: The transformation function.
///
/// # Note
/// The transformation function takes an ARGB pixel as input and returns an ARGB pixel as output.
/// This function will be applied to all pixels of the image.
pub fn transform(&mut self, trans: impl Fn(ARGB) -> ARGB) {
for pixel in self.getbuffer_mut().iter_mut() {
*pixel = trans(*pixel);
}
}
/// Apply a template to the image.
///
/// # Parameters
/// - `mask`: The template mask.
/// - `apply`: The mask channels to apply.
/// - `mode`: The template mode.
///
/// # Returns
/// A new `Image` object.
pub fn template<const N: usize>(
&mut self,
mask: SMatrix<f32, N, N>,
apply: ApplyMask,
mode: TemplateMode,
) -> Self {
#[cfg(debug_assertions)]
assert!(N % 2 == 1, "The template size must be odd.");
let width = self.getwidth();
let height = self.getheight();
let mut img = Image::new(width, height);
let src = self.getbuffer();
let dst = img.getbuffer_mut();
for i in 0..height {
for j in 0..width {
let (mut sum_red, mut sum_green, mut sum_blue) = (0.0, 0.0, 0.0);
let mut is_dont_care = false;
'dor_care: for m in 0..N as u32 {
for n in 0..N as u32 {
let x = (i + m) as i32 - N as i32 / 2;
let y = (j + n) as i32 - N as i32 / 2;
let c;
if x < 0 || x >= height as i32 || y < 0 || y >= width as i32 {
match mode {
TemplateMode::White => c = 0xFFFFFF,
TemplateMode::Black => c = 0x0,
TemplateMode::Ignore => continue,
TemplateMode::DotCare => {
is_dont_care = true;
break 'dor_care;
}
}
} else {
c = src[(x as u32 * width + y as u32) as usize];
}
if apply.contains(ApplyMask::Red) {
sum_red += mask[(m as usize, n as usize)] * ((c >> 16) & 0xFF) as f32;
}
if apply.contains(ApplyMask::Green) {
sum_green += mask[(m as usize, n as usize)] * ((c >> 8) & 0xFF) as f32;
}
if apply.contains(ApplyMask::Blue) {
sum_blue += mask[(m as usize, n as usize)] * (c & 0xFF) as f32;
}
}
}
if !is_dont_care {
let red = sum_red.max(0.0).min(255.0) as u8;
let green = sum_green.max(0.0).min(255.0) as u8;
let blue = sum_blue.max(0.0).min(255.0) as u8;
let alpha = 0xFF;
dst[(i * width + j) as usize] = ((alpha as u32) << 24)
| ((red as u32) << 16)
| ((green as u32) << 8)
| blue as u32;
}
}
}
img
}
}