chore: run cargo fmt on everything

This commit is contained in:
Nathan Fiedler
2024-05-25 10:50:27 -07:00
parent 320cfb6e62
commit aedcfcd8f7
42 changed files with 637 additions and 777 deletions

View File

@ -37,13 +37,13 @@ use libc::size_t;
pub use conversions::ToMagick; pub use conversions::ToMagick;
pub use result::MagickError; pub use result::MagickError;
use result::Result; use result::Result;
pub use wand::*;
pub use types::*; pub use types::*;
pub use wand::*;
mod conversions; mod conversions;
mod result; mod result;
mod wand;
mod types; mod types;
mod wand;
include!(concat!(env!("OUT_DIR"), "/bindings.rs")); include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
/// This function must be called before any other ImageMagick operations /// This function must be called before any other ImageMagick operations
@ -73,7 +73,9 @@ pub fn magick_query_fonts(pattern: &str) -> Result<Vec<String>> {
let ptr = let ptr =
unsafe { bindings::MagickQueryFonts(c_string.as_ptr(), &mut number_fonts as *mut size_t) }; unsafe { bindings::MagickQueryFonts(c_string.as_ptr(), &mut number_fonts as *mut size_t) };
if ptr.is_null() { if ptr.is_null() {
Err(MagickError("null ptr returned by magick_query_fonts".to_string())) Err(MagickError(
"null ptr returned by magick_query_fonts".to_string(),
))
} else { } else {
let mut v = Vec::new(); let mut v = Vec::new();
let c_str_ptr_slice = unsafe { ::std::slice::from_raw_parts(ptr, number_fonts as usize) }; let c_str_ptr_slice = unsafe { ::std::slice::from_raw_parts(ptr, number_fonts as usize) };

View File

@ -39,32 +39,32 @@ impl Default for ChannelType {
impl From<ChannelType> for bindings::ChannelType { impl From<ChannelType> for bindings::ChannelType {
fn from(value: ChannelType) -> Self { fn from(value: ChannelType) -> Self {
match value { match value {
ChannelType::Undefined => { bindings::ChannelType_UndefinedChannel }, ChannelType::Undefined => bindings::ChannelType_UndefinedChannel,
ChannelType::RedChannel => { bindings::ChannelType_RedChannel }, ChannelType::RedChannel => bindings::ChannelType_RedChannel,
ChannelType::GrayChannel => { bindings::ChannelType_GrayChannel }, ChannelType::GrayChannel => bindings::ChannelType_GrayChannel,
ChannelType::CyanChannel => { bindings::ChannelType_CyanChannel }, ChannelType::CyanChannel => bindings::ChannelType_CyanChannel,
ChannelType::LChannel => { bindings::ChannelType_LChannel }, ChannelType::LChannel => bindings::ChannelType_LChannel,
ChannelType::GreenChannel => { bindings::ChannelType_GreenChannel }, ChannelType::GreenChannel => bindings::ChannelType_GreenChannel,
ChannelType::MagentaChannel => { bindings::ChannelType_MagentaChannel }, ChannelType::MagentaChannel => bindings::ChannelType_MagentaChannel,
ChannelType::aChannel => { bindings::ChannelType_aChannel }, ChannelType::aChannel => bindings::ChannelType_aChannel,
ChannelType::BlueChannel => { bindings::ChannelType_BlueChannel }, ChannelType::BlueChannel => bindings::ChannelType_BlueChannel,
ChannelType::bChannel => { bindings::ChannelType_bChannel }, ChannelType::bChannel => bindings::ChannelType_bChannel,
ChannelType::YellowChannel => { bindings::ChannelType_YellowChannel }, ChannelType::YellowChannel => bindings::ChannelType_YellowChannel,
ChannelType::BlackChannel => { bindings::ChannelType_BlackChannel }, ChannelType::BlackChannel => bindings::ChannelType_BlackChannel,
ChannelType::AlphaChannel => { bindings::ChannelType_AlphaChannel }, ChannelType::AlphaChannel => bindings::ChannelType_AlphaChannel,
ChannelType::OpacityChannel => { bindings::ChannelType_OpacityChannel }, ChannelType::OpacityChannel => bindings::ChannelType_OpacityChannel,
ChannelType::IndexChannel => { bindings::ChannelType_IndexChannel }, ChannelType::IndexChannel => bindings::ChannelType_IndexChannel,
ChannelType::ReadMaskChannel => { bindings::ChannelType_ReadMaskChannel }, ChannelType::ReadMaskChannel => bindings::ChannelType_ReadMaskChannel,
ChannelType::WriteMaskChannel => { bindings::ChannelType_WriteMaskChannel }, ChannelType::WriteMaskChannel => bindings::ChannelType_WriteMaskChannel,
ChannelType::MetaChannel => { bindings::ChannelType_MetaChannel }, ChannelType::MetaChannel => bindings::ChannelType_MetaChannel,
ChannelType::CompositeMaskChannel => { bindings::ChannelType_CompositeMaskChannel }, ChannelType::CompositeMaskChannel => bindings::ChannelType_CompositeMaskChannel,
ChannelType::CompositeChannels => { bindings::ChannelType_CompositeChannels }, ChannelType::CompositeChannels => bindings::ChannelType_CompositeChannels,
ChannelType::AllChannels => { bindings::ChannelType_AllChannels }, ChannelType::AllChannels => bindings::ChannelType_AllChannels,
ChannelType::TrueAlphaChannel => { bindings::ChannelType_TrueAlphaChannel }, ChannelType::TrueAlphaChannel => bindings::ChannelType_TrueAlphaChannel,
ChannelType::RGBChannels => { bindings::ChannelType_RGBChannels }, ChannelType::RGBChannels => bindings::ChannelType_RGBChannels,
ChannelType::GrayChannels => { bindings::ChannelType_GrayChannels }, ChannelType::GrayChannels => bindings::ChannelType_GrayChannels,
ChannelType::SyncChannels => { bindings::ChannelType_SyncChannels }, ChannelType::SyncChannels => bindings::ChannelType_SyncChannels,
ChannelType::DefaultChannels => { bindings::ChannelType_DefaultChannels }, ChannelType::DefaultChannels => bindings::ChannelType_DefaultChannels,
} }
} }
} }
@ -73,33 +73,33 @@ impl From<bindings::ChannelType> for ChannelType {
fn from(value: bindings::ChannelType) -> Self { fn from(value: bindings::ChannelType) -> Self {
// Unreachable match arms commented out // Unreachable match arms commented out
match value { match value {
bindings::ChannelType_UndefinedChannel => { ChannelType::Undefined }, bindings::ChannelType_UndefinedChannel => ChannelType::Undefined,
bindings::ChannelType_RedChannel => { ChannelType::RedChannel }, bindings::ChannelType_RedChannel => ChannelType::RedChannel,
// bindings::ChannelType_GrayChannel => { ChannelType::GrayChannel }, // bindings::ChannelType_GrayChannel => { ChannelType::GrayChannel },
// bindings::ChannelType_CyanChannel => { ChannelType::CyanChannel }, // bindings::ChannelType_CyanChannel => { ChannelType::CyanChannel },
// bindings::ChannelType_LChannel => { ChannelType::LChannel }, // bindings::ChannelType_LChannel => { ChannelType::LChannel },
bindings::ChannelType_GreenChannel => { ChannelType::GreenChannel }, bindings::ChannelType_GreenChannel => ChannelType::GreenChannel,
// bindings::ChannelType_MagentaChannel => { ChannelType::MagentaChannel }, // bindings::ChannelType_MagentaChannel => { ChannelType::MagentaChannel },
// bindings::ChannelType_aChannel => { ChannelType::aChannel }, // bindings::ChannelType_aChannel => { ChannelType::aChannel },
bindings::ChannelType_BlueChannel => { ChannelType::BlueChannel }, bindings::ChannelType_BlueChannel => ChannelType::BlueChannel,
// bindings::ChannelType_bChannel => { ChannelType::bChannel }, // bindings::ChannelType_bChannel => { ChannelType::bChannel },
// bindings::ChannelType_YellowChannel => { ChannelType::YellowChannel }, // bindings::ChannelType_YellowChannel => { ChannelType::YellowChannel },
bindings::ChannelType_BlackChannel => { ChannelType::BlackChannel }, bindings::ChannelType_BlackChannel => ChannelType::BlackChannel,
bindings::ChannelType_AlphaChannel => { ChannelType::AlphaChannel }, bindings::ChannelType_AlphaChannel => ChannelType::AlphaChannel,
// bindings::ChannelType_OpacityChannel => { ChannelType::OpacityChannel }, // bindings::ChannelType_OpacityChannel => { ChannelType::OpacityChannel },
bindings::ChannelType_IndexChannel => { ChannelType::IndexChannel }, bindings::ChannelType_IndexChannel => ChannelType::IndexChannel,
bindings::ChannelType_ReadMaskChannel => { ChannelType::ReadMaskChannel }, bindings::ChannelType_ReadMaskChannel => ChannelType::ReadMaskChannel,
bindings::ChannelType_WriteMaskChannel => { ChannelType::WriteMaskChannel }, bindings::ChannelType_WriteMaskChannel => ChannelType::WriteMaskChannel,
bindings::ChannelType_MetaChannel => { ChannelType::MetaChannel }, bindings::ChannelType_MetaChannel => ChannelType::MetaChannel,
bindings::ChannelType_CompositeMaskChannel => { ChannelType::CompositeMaskChannel }, bindings::ChannelType_CompositeMaskChannel => ChannelType::CompositeMaskChannel,
bindings::ChannelType_CompositeChannels => { ChannelType::CompositeChannels }, bindings::ChannelType_CompositeChannels => ChannelType::CompositeChannels,
bindings::ChannelType_AllChannels => { ChannelType::AllChannels }, bindings::ChannelType_AllChannels => ChannelType::AllChannels,
// bindings::ChannelType_TrueAlphaChannel => { ChannelType::TrueAlphaChannel }, // bindings::ChannelType_TrueAlphaChannel => { ChannelType::TrueAlphaChannel },
// bindings::ChannelType_RGBChannels => { ChannelType::RGBChannels }, // bindings::ChannelType_RGBChannels => { ChannelType::RGBChannels },
bindings::ChannelType_GrayChannels => { ChannelType::GrayChannels }, bindings::ChannelType_GrayChannels => ChannelType::GrayChannels,
bindings::ChannelType_SyncChannels => { ChannelType::SyncChannels }, bindings::ChannelType_SyncChannels => ChannelType::SyncChannels,
// bindings::ChannelType_DefaultChannels => { ChannelType::DefaultChannels }, // bindings::ChannelType_DefaultChannels => { ChannelType::DefaultChannels },
_ => { ChannelType::Undefined }, _ => ChannelType::Undefined,
} }
} }
} }

View File

@ -11,7 +11,7 @@ impl Image<'_> {
pub unsafe fn new(img: *mut bindings::Image) -> Self { pub unsafe fn new(img: *mut bindings::Image) -> Self {
Image { Image {
image: img, image: img,
phantom_data: PhantomData phantom_data: PhantomData,
} }
} }

View File

@ -1,7 +1,7 @@
use std::ffi::CString; use std::ffi::CString;
use crate::bindings; use crate::bindings;
use crate::{Result, MagickError}; use crate::{MagickError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)] #[repr(u32)]
@ -58,9 +58,6 @@ impl From<KernelInfoType> for bindings::KernelInfoType {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)] #[repr(u32)]
pub enum MorphologyMethod { pub enum MorphologyMethod {
@ -101,9 +98,6 @@ impl From<MorphologyMethod> for bindings::KernelInfoType {
} }
} }
/// Builder, that creates instances of [KernelInfo](self::KernelInfo) /// Builder, that creates instances of [KernelInfo](self::KernelInfo)
/// ///
/// # Examples /// # Examples
@ -197,28 +191,25 @@ impl KernelBuilder {
} }
pub fn build(&self) -> Result<KernelInfo> { pub fn build(&self) -> Result<KernelInfo> {
let size = self.size.ok_or(MagickError("no kernel size given".to_string()))?; let size = self
let values = self.values.as_ref().ok_or(MagickError("no kernel values given".to_string()))?; .size
.ok_or(MagickError("no kernel size given".to_string()))?;
let values = self
.values
.as_ref()
.ok_or(MagickError("no kernel values given".to_string()))?;
if values.len() != size.0 * size.1 { if values.len() != size.0 * size.1 {
return Err(MagickError("kernel size doesn't match kernel values size".to_string())); return Err(MagickError(
"kernel size doesn't match kernel values size".to_string(),
));
} }
// Create kernel string // Create kernel string
let mut kernel_string = if let Some(center) = self.center { let mut kernel_string = if let Some(center) = self.center {
format!( format!("{}x{}+{}+{}:", size.0, size.1, center.0, center.1)
"{}x{}+{}+{}:",
size.0,
size.1,
center.0,
center.1
)
} else { } else {
format!( format!("{}x{}:", size.0, size.1,)
"{}x{}:",
size.0,
size.1,
)
}; };
// Add values // Add values
@ -233,12 +224,8 @@ impl KernelBuilder {
let c_kernel_string = CString::new(kernel_string).expect("CString::new() has failed"); let c_kernel_string = CString::new(kernel_string).expect("CString::new() has failed");
// Create kernel info // Create kernel info
let kernel_info = unsafe { let kernel_info =
bindings::AcquireKernelInfo( unsafe { bindings::AcquireKernelInfo(c_kernel_string.as_ptr(), std::ptr::null_mut()) };
c_kernel_string.as_ptr(),
std::ptr::null_mut()
)
};
if kernel_info.is_null() { if kernel_info.is_null() {
return Err(MagickError("failed to acquire kernel info".to_string())); return Err(MagickError("failed to acquire kernel info".to_string()));
@ -260,20 +247,22 @@ impl KernelBuilder {
} }
pub fn build_builtin(&self) -> Result<KernelInfo> { pub fn build_builtin(&self) -> Result<KernelInfo> {
let info_type = self.info_type.ok_or(MagickError("no info type given".to_string()))?; let info_type = self
let mut geom_info = self.geom_info.ok_or(MagickError("no geometry info given".to_string()))?; .info_type
.ok_or(MagickError("no info type given".to_string()))?;
let mut geom_info = self
.geom_info
.ok_or(MagickError("no geometry info given".to_string()))?;
// Create kernel info // Create kernel info
let kernel_info = unsafe { let kernel_info = unsafe {
bindings::AcquireKernelBuiltIn( bindings::AcquireKernelBuiltIn(info_type.into(), &mut geom_info, std::ptr::null_mut())
info_type.into(),
&mut geom_info,
std::ptr::null_mut()
)
}; };
if kernel_info.is_null() { if kernel_info.is_null() {
return Err(MagickError("failed to acquire builtin kernel info".to_string())); return Err(MagickError(
"failed to acquire builtin kernel info".to_string(),
));
} }
Ok(KernelInfo::new(kernel_info)) Ok(KernelInfo::new(kernel_info))
@ -286,20 +275,12 @@ pub struct KernelInfo {
impl KernelInfo { impl KernelInfo {
fn new(kernel_info: *mut bindings::KernelInfo) -> KernelInfo { fn new(kernel_info: *mut bindings::KernelInfo) -> KernelInfo {
return KernelInfo { return KernelInfo { kernel_info };
kernel_info
};
} }
/// The values within the kernel is scaled directly using given scaling factor without change. /// The values within the kernel is scaled directly using given scaling factor without change.
pub fn scale(&mut self, factor: f64) { pub fn scale(&mut self, factor: f64) {
unsafe { unsafe { bindings::ScaleKernelInfo(self.kernel_info, factor, 0) }
bindings::ScaleKernelInfo(
self.kernel_info,
factor,
0
)
}
} }
/// Kernel normalization is designed to ensure that any use of the kernel scaling factor with /// Kernel normalization is designed to ensure that any use of the kernel scaling factor with
@ -323,7 +304,7 @@ impl KernelInfo {
bindings::ScaleKernelInfo( bindings::ScaleKernelInfo(
self.kernel_info, self.kernel_info,
1.0, 1.0,
bindings::GeometryFlags_NormalizeValue bindings::GeometryFlags_NormalizeValue,
) )
} }
} }
@ -337,7 +318,7 @@ impl KernelInfo {
bindings::ScaleKernelInfo( bindings::ScaleKernelInfo(
self.kernel_info, self.kernel_info,
1.0, 1.0,
bindings::GeometryFlags_CorrelateNormalizeValue bindings::GeometryFlags_CorrelateNormalizeValue,
) )
} }
} }
@ -350,12 +331,7 @@ impl KernelInfo {
/// The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp /// The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp
/// kernels or into sharpening kernels. /// kernels or into sharpening kernels.
pub fn unity_add(&mut self, scale: f64) { pub fn unity_add(&mut self, scale: f64) {
unsafe { unsafe { bindings::UnityAddKernelInfo(self.kernel_info, scale) }
bindings::UnityAddKernelInfo(
self.kernel_info,
scale
)
}
} }
pub unsafe fn get_ptr(&self) -> *mut bindings::KernelInfo { pub unsafe fn get_ptr(&self) -> *mut bindings::KernelInfo {
@ -371,9 +347,7 @@ impl Drop for KernelInfo {
impl Clone for KernelInfo { impl Clone for KernelInfo {
fn clone(&self) -> Self { fn clone(&self) -> Self {
let kernel_info = unsafe { let kernel_info = unsafe { bindings::CloneKernelInfo(self.kernel_info) };
bindings::CloneKernelInfo(self.kernel_info)
};
if kernel_info.is_null() { if kernel_info.is_null() {
panic!("failed to clone kernel info"); panic!("failed to clone kernel info");

View File

@ -7,7 +7,8 @@ pub enum MetricType {
MeanAbsolute = bindings::MetricType_MeanAbsoluteErrorMetric as isize, MeanAbsolute = bindings::MetricType_MeanAbsoluteErrorMetric as isize,
MeanErrorPerPixel = bindings::MetricType_MeanErrorPerPixelErrorMetric as isize, MeanErrorPerPixel = bindings::MetricType_MeanErrorPerPixelErrorMetric as isize,
MeanSquared = bindings::MetricType_MeanSquaredErrorMetric as isize, MeanSquared = bindings::MetricType_MeanSquaredErrorMetric as isize,
NormalizedCrossCorrelation = bindings::MetricType_NormalizedCrossCorrelationErrorMetric as isize, NormalizedCrossCorrelation =
bindings::MetricType_NormalizedCrossCorrelationErrorMetric as isize,
PeakAbsolute = bindings::MetricType_PeakAbsoluteErrorMetric as isize, PeakAbsolute = bindings::MetricType_PeakAbsoluteErrorMetric as isize,
PeakSignalToNoiseRatio = bindings::MetricType_PeakSignalToNoiseRatioErrorMetric as isize, PeakSignalToNoiseRatio = bindings::MetricType_PeakSignalToNoiseRatioErrorMetric as isize,
PerceptualHash = bindings::MetricType_PerceptualHashErrorMetric as isize, PerceptualHash = bindings::MetricType_PerceptualHashErrorMetric as isize,

View File

@ -21,16 +21,8 @@ use bindings;
use crate::result::MagickError; use crate::result::MagickError;
use crate::result::Result; use crate::result::Result;
use crate::{ use crate::{
AlignType, AlignType, ClipPathUnits, DecorationType, DirectionType, FillRule, GravityType, LineCap,
ClipPathUnits, LineJoin, StretchType, StyleType,
DecorationType,
DirectionType,
FillRule,
GravityType,
LineCap,
LineJoin,
StretchType,
StyleType,
}; };
wand_common!( wand_common!(

View File

@ -40,11 +40,9 @@ macro_rules! wand_common {
pub fn clear_exception(&mut self) -> Result<()> { pub fn clear_exception(&mut self) -> Result<()> {
match unsafe { ::bindings::$clear_exc(self.wand) } { match unsafe { ::bindings::$clear_exc(self.wand) } {
::bindings::MagickBooleanType_MagickTrue => Ok(()), ::bindings::MagickBooleanType_MagickTrue => Ok(()),
_ => Err(MagickError(concat!( _ => Err(MagickError(
"failed to clear", concat!("failed to clear", stringify!($wand), "exception").to_string(),
stringify!($wand), )),
"exception"
).to_string())),
} }
} }
@ -58,17 +56,14 @@ macro_rules! wand_common {
let ptr = unsafe { ::bindings::$get_exc(self.wand, &mut severity as *mut _) }; let ptr = unsafe { ::bindings::$get_exc(self.wand, &mut severity as *mut _) };
if ptr.is_null() { if ptr.is_null() {
Err(MagickError(concat!( Err(MagickError(
"null ptr returned by", concat!("null ptr returned by", stringify!($wand), "get_exception")
stringify!($wand), .to_string(),
"get_exception" ))
).to_string()))
} else { } else {
let c_str = unsafe { CStr::from_ptr(ptr) }; let c_str = unsafe { CStr::from_ptr(ptr) };
let exception = c_str.to_string_lossy().into_owned(); let exception = c_str.to_string_lossy().into_owned();
unsafe { unsafe { ::bindings::RelinquishMagickMemory(ptr as *mut ::libc::c_void) };
::bindings::RelinquishMagickMemory(ptr as *mut ::libc::c_void)
};
Ok((exception, severity)) Ok((exception, severity))
} }
} }
@ -76,7 +71,9 @@ macro_rules! wand_common {
pub fn is_wand(&self) -> Result<()> { pub fn is_wand(&self) -> Result<()> {
match unsafe { ::bindings::$is_wand(self.wand) } { match unsafe { ::bindings::$is_wand(self.wand) } {
::bindings::MagickBooleanType_MagickTrue => Ok(()), ::bindings::MagickBooleanType_MagickTrue => Ok(()),
_ => Err(MagickError(concat!(stringify!($wand), " not a wand").to_string())), _ => Err(MagickError(
concat!(stringify!($wand), " not a wand").to_string(),
)),
} }
} }
} }
@ -159,10 +156,9 @@ macro_rules! string_get {
pub fn $get(&self) -> Result<String> { pub fn $get(&self) -> Result<String> {
let ptr = unsafe { ::bindings::$c_get(self.wand) }; let ptr = unsafe { ::bindings::$c_get(self.wand) };
if ptr.is_null() { if ptr.is_null() {
Err(MagickError(concat!( Err(MagickError(
"null ptr returned by ", concat!("null ptr returned by ", stringify!($get)).to_string(),
stringify!($get) ))
).to_string()))
} else { } else {
let c_str = unsafe { ::std::ffi::CStr::from_ptr(ptr) }; let c_str = unsafe { ::std::ffi::CStr::from_ptr(ptr) };
let result: String = c_str.to_string_lossy().into_owned(); let result: String = c_str.to_string_lossy().into_owned();

View File

@ -26,38 +26,16 @@ use result::MagickError;
#[cfg(not(target_os = "freebsd"))] #[cfg(not(target_os = "freebsd"))]
use size_t; use size_t;
use super::{MagickFalse, MagickTrue};
use crate::result::Result; use crate::result::Result;
use super::{MagickTrue, MagickFalse};
use super::{DrawingWand, PixelWand}; use super::{DrawingWand, PixelWand};
use crate::{ use crate::{
AlphaChannelOption, AlphaChannelOption, AutoThresholdMethod, ChannelType, ColorspaceType, CompositeOperator,
AutoThresholdMethod, CompressionType, DisposeType, DitherMethod, EndianType, FilterType, GravityType, Image,
ChannelType, ImageType, InterlaceType, KernelInfo, LayerMethod, MagickEvaluateOperator, MagickFunction,
ColorspaceType, MetricType, MorphologyMethod, OrientationType, PixelInterpolateMethod, PixelMask,
CompositeOperator, RenderingIntent, ResolutionType, ResourceType, StatisticType,
CompressionType,
DisposeType,
DitherMethod,
EndianType,
FilterType,
GravityType,
Image,
ImageType,
InterlaceType,
KernelInfo,
LayerMethod,
MagickEvaluateOperator,
MagickFunction,
MetricType,
MorphologyMethod,
OrientationType,
PixelInterpolateMethod,
PixelMask,
RenderingIntent,
ResolutionType,
ResourceType,
StatisticType,
}; };
wand_common!( wand_common!(
@ -83,19 +61,21 @@ impl MagickWand {
/// ///
/// * `img`: the image. /// * `img`: the image.
pub fn new_from_image(img: &Image<'_>) -> Result<MagickWand> { pub fn new_from_image(img: &Image<'_>) -> Result<MagickWand> {
let result = unsafe { let result = unsafe { bindings::NewMagickWandFromImage(img.get_ptr()) };
bindings::NewMagickWandFromImage(img.get_ptr())
};
return if result.is_null() { return if result.is_null() {
Err(MagickError("failed to create magick wand from image".to_string())) Err(MagickError(
"failed to create magick wand from image".to_string(),
))
} else { } else {
Ok(MagickWand { wand: result }) Ok(MagickWand { wand: result })
} };
} }
pub fn new_image(&self, columns: usize, rows: usize, background: &PixelWand) -> Result<()> { pub fn new_image(&self, columns: usize, rows: usize, background: &PixelWand) -> Result<()> {
match unsafe { bindings::MagickNewImage(self.wand, columns.into(), rows.into(), background.wand) } { match unsafe {
bindings::MagickNewImage(self.wand, columns.into(), rows.into(), background.wand)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -105,10 +85,7 @@ impl MagickWand {
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn set_resource_limit(resource: ResourceType, limit: u64) -> Result<()> { pub fn set_resource_limit(resource: ResourceType, limit: u64) -> Result<()> {
let result = unsafe { let result = unsafe {
bindings::SetMagickResourceLimit( bindings::SetMagickResourceLimit(resource.into(), limit as bindings::MagickSizeType)
resource.into(),
limit as bindings::MagickSizeType,
)
}; };
match result { match result {
MagickTrue => Ok(()), MagickTrue => Ok(()),
@ -261,9 +238,7 @@ impl MagickWand {
/// MosaicLayer: Start with the virtual canvas of the first image, enlarging left and right /// MosaicLayer: Start with the virtual canvas of the first image, enlarging left and right
/// edges to contain all images. Images with negative offsets will be clipped. /// edges to contain all images. Images with negative offsets will be clipped.
pub fn merge_image_layers(&self, method: LayerMethod) -> Result<MagickWand> { pub fn merge_image_layers(&self, method: LayerMethod) -> Result<MagickWand> {
let result = unsafe { let result = unsafe { bindings::MagickMergeImageLayers(self.wand, method.into()) };
bindings::MagickMergeImageLayers(self.wand, method.into())
};
if result.is_null() { if result.is_null() {
return Err(MagickError("failed to merge image layers".to_string())); return Err(MagickError("failed to merge image layers".to_string()));
} }
@ -357,11 +332,7 @@ impl MagickWand {
} }
// Replaces colors in the image from a color lookup table. // Replaces colors in the image from a color lookup table.
pub fn clut_image( pub fn clut_image(&self, clut_wand: &MagickWand, method: PixelInterpolateMethod) -> Result<()> {
&self,
clut_wand: &MagickWand,
method: PixelInterpolateMethod,
) -> Result<()> {
let result = unsafe { bindings::MagickClutImage(self.wand, clut_wand.wand, method.into()) }; let result = unsafe { bindings::MagickClutImage(self.wand, clut_wand.wand, method.into()) };
match result { match result {
MagickTrue => Ok(()), MagickTrue => Ok(()),
@ -378,7 +349,8 @@ impl MagickWand {
} }
pub fn fx(&mut self, expression: &str) -> Result<MagickWand> { pub fn fx(&mut self, expression: &str) -> Result<MagickWand> {
let c_expression = CString::new(expression).map_err(|_| "expression string contains null byte")?; let c_expression =
CString::new(expression).map_err(|_| "expression string contains null byte")?;
let wand = unsafe { bindings::MagickFxImage(self.wand, c_expression.as_ptr()) }; let wand = unsafe { bindings::MagickFxImage(self.wand, c_expression.as_ptr()) };
if wand.is_null() { if wand.is_null() {
Err(MagickError("failed to fx the image".to_string())) Err(MagickError("failed to fx the image".to_string()))
@ -411,7 +383,9 @@ impl MagickWand {
16 => Ok(65535.0f64), 16 => Ok(65535.0f64),
32 => Ok(4294967295.0f64), 32 => Ok(4294967295.0f64),
64 => Ok(18446744073709551615.0f64), 64 => Ok(18446744073709551615.0f64),
_ => Err(MagickError("Quantum depth must be one of 8, 16, 32 or 64".to_string())), _ => Err(MagickError(
"Quantum depth must be one of 8, 16, 32 or 64".to_string(),
)),
} }
} }
@ -456,14 +430,8 @@ impl MagickWand {
//MagickNormalizeImage enhances the contrast of a color image by adjusting the pixels color //MagickNormalizeImage enhances the contrast of a color image by adjusting the pixels color
//to span the entire range of colors available //to span the entire range of colors available
pub fn normalize_image( pub fn normalize_image(&self) -> Result<()> {
&self, let result = unsafe { bindings::MagickNormalizeImage(self.wand) };
) -> Result<()> {
let result = unsafe {
bindings::MagickNormalizeImage(
self.wand,
)
};
match result { match result {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
@ -473,18 +441,12 @@ impl MagickWand {
//MagickOrderedDitherImage performs an ordered dither based on a number of pre-defined //MagickOrderedDitherImage performs an ordered dither based on a number of pre-defined
//dithering threshold maps, but over multiple intensity levels, which can be different for //dithering threshold maps, but over multiple intensity levels, which can be different for
//different channels, according to the input arguments. //different channels, according to the input arguments.
pub fn ordered_dither_image( pub fn ordered_dither_image(&self, threshold_map: &str) -> Result<()> {
&self, let c_threshold_map =
threshold_map: &str, CString::new(threshold_map).map_err(|_| "threshold_map string contains null byte")?;
) -> Result<()> {
let c_threshold_map = CString::new(threshold_map).map_err(|_| "threshold_map string contains null byte")?;
let result = unsafe { let result =
bindings::MagickOrderedDitherImage( unsafe { bindings::MagickOrderedDitherImage(self.wand, c_threshold_map.as_ptr()) };
self.wand,
c_threshold_map.as_ptr(),
)
};
match result { match result {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
@ -576,9 +538,7 @@ impl MagickWand {
} }
pub fn negate_image(&self) -> Result<()> { pub fn negate_image(&self) -> Result<()> {
let result = unsafe { let result = unsafe { bindings::MagickNegateImage(self.wand, MagickTrue) };
bindings::MagickNegateImage(self.wand, MagickTrue)
};
match result { match result {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
@ -625,7 +585,7 @@ impl MagickWand {
self.wand, self.wand,
statistic_type.into(), statistic_type.into(),
width.into(), width.into(),
height.into() height.into(),
) )
} { } {
MagickTrue => Ok(()), MagickTrue => Ok(()),
@ -687,12 +647,11 @@ impl MagickWand {
/// Reset the Wand page canvas and position. /// Reset the Wand page canvas and position.
pub fn reset_image_page(&self, page_geometry: &str) -> Result<()> { pub fn reset_image_page(&self, page_geometry: &str) -> Result<()> {
let c_page_geometry = CString::new(page_geometry).map_err(|_| "page_geometry contains null byte")?; let c_page_geometry =
match unsafe { CString::new(page_geometry).map_err(|_| "page_geometry contains null byte")?;
bindings::MagickResetImagePage(self.wand, c_page_geometry.as_ptr()) match unsafe { bindings::MagickResetImagePage(self.wand, c_page_geometry.as_ptr()) } {
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)) _ => Err(MagickError(self.get_exception()?.0)),
} }
} }
@ -700,20 +659,18 @@ impl MagickWand {
/// ///
/// * `artifact`: the artifact. /// * `artifact`: the artifact.
pub fn get_image_artifact(&self, artifact: &str) -> Result<String> { pub fn get_image_artifact(&self, artifact: &str) -> Result<String> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?; let c_artifact =
CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_value = unsafe { let c_value = unsafe { bindings::MagickGetImageArtifact(self.wand, c_artifact.as_ptr()) };
bindings::MagickGetImageArtifact(
self.wand,
c_artifact.as_ptr()
)
};
if c_value.is_null() { if c_value.is_null() {
return Err(MagickError(format!("missing artifact: {}", artifact))); return Err(MagickError(format!("missing artifact: {}", artifact)));
} }
// convert (and copy) the C string to a Rust string // convert (and copy) the C string to a Rust string
let value = unsafe { CStr::from_ptr(c_value) }.to_string_lossy().into_owned(); let value = unsafe { CStr::from_ptr(c_value) }
.to_string_lossy()
.into_owned();
unsafe { unsafe {
bindings::MagickRelinquishMemory(c_value as *mut c_void); bindings::MagickRelinquishMemory(c_value as *mut c_void);
@ -723,15 +680,12 @@ impl MagickWand {
} }
pub fn get_image_artifacts(&self, pattern: &str) -> Result<Vec<String>> { pub fn get_image_artifacts(&self, pattern: &str) -> Result<Vec<String>> {
let c_pattern = CString::new(pattern).map_err(|_| MagickError("artifact string contains null byte".to_string()))?; let c_pattern = CString::new(pattern)
.map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let mut num_of_artifacts: size_t = 0; let mut num_of_artifacts: size_t = 0;
let c_values = unsafe { let c_values = unsafe {
bindings::MagickGetImageArtifacts( bindings::MagickGetImageArtifacts(self.wand, c_pattern.as_ptr(), &mut num_of_artifacts)
self.wand,
c_pattern.as_ptr(),
&mut num_of_artifacts
)
}; };
if c_values.is_null() { if c_values.is_null() {
@ -782,20 +736,13 @@ impl MagickWand {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub fn set_image_artifact( pub fn set_image_artifact(&mut self, artifact: &str, value: &str) -> Result<()> {
&mut self, let c_artifact =
artifact: &str, CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
value: &str
) -> Result<()> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_value = CString::new(value).map_err(|_| "value string contains null byte")?; let c_value = CString::new(value).map_err(|_| "value string contains null byte")?;
let result = unsafe { let result = unsafe {
bindings::MagickSetImageArtifact( bindings::MagickSetImageArtifact(self.wand, c_artifact.as_ptr(), c_value.as_ptr())
self.wand,
c_artifact.as_ptr(),
c_value.as_ptr()
)
}; };
match result { match result {
@ -808,14 +755,10 @@ impl MagickWand {
/// ///
/// * `artifact`: the artifact. /// * `artifact`: the artifact.
pub fn delete_image_artifact(&mut self, artifact: &str) -> Result<()> { pub fn delete_image_artifact(&mut self, artifact: &str) -> Result<()> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?; let c_artifact =
CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
match unsafe { match unsafe { bindings::MagickDeleteImageArtifact(self.wand, c_artifact.as_ptr()) } {
bindings::MagickDeleteImageArtifact(
self.wand,
c_artifact.as_ptr()
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(format!("missing artifact: {}", artifact))), _ => Err(MagickError(format!("missing artifact: {}", artifact))),
} }
@ -831,7 +774,9 @@ impl MagickWand {
} }
// convert (and copy) the C string to a Rust string // convert (and copy) the C string to a Rust string
let value = unsafe { CStr::from_ptr(c_value) }.to_string_lossy().into_owned(); let value = unsafe { CStr::from_ptr(c_value) }
.to_string_lossy()
.into_owned();
unsafe { unsafe {
bindings::MagickRelinquishMemory(c_value as *mut c_void); bindings::MagickRelinquishMemory(c_value as *mut c_void);
@ -841,15 +786,12 @@ impl MagickWand {
} }
pub fn get_image_properties(&self, pattern: &str) -> Result<Vec<String>> { pub fn get_image_properties(&self, pattern: &str) -> Result<Vec<String>> {
let c_pattern = CString::new(pattern).map_err(|_| MagickError("artifact string contains null byte".to_string()))?; let c_pattern = CString::new(pattern)
.map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let mut num_of_artifacts: size_t = 0; let mut num_of_artifacts: size_t = 0;
let c_values = unsafe { let c_values = unsafe {
bindings::MagickGetImageProperties( bindings::MagickGetImageProperties(self.wand, c_pattern.as_ptr(), &mut num_of_artifacts)
self.wand,
c_pattern.as_ptr(),
&mut num_of_artifacts
)
}; };
if c_values.is_null() { if c_values.is_null() {
@ -886,9 +828,7 @@ impl MagickWand {
pub fn get_image_pixel_color(&self, x: isize, y: isize) -> Option<PixelWand> { pub fn get_image_pixel_color(&self, x: isize, y: isize) -> Option<PixelWand> {
let pw = PixelWand::new(); let pw = PixelWand::new();
match unsafe { match unsafe { bindings::MagickGetImagePixelColor(self.wand, x, y, pw.wand) } {
bindings::MagickGetImagePixelColor(self.wand, x, y, pw.wand)
} {
MagickTrue => Some(pw), MagickTrue => Some(pw),
_ => None, _ => None,
} }
@ -972,9 +912,7 @@ impl MagickWand {
/// Sets the image resolution /// Sets the image resolution
pub fn set_image_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> { pub fn set_image_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> {
match unsafe { match unsafe { bindings::MagickSetImageResolution(self.wand, x_resolution, y_resolution) } {
bindings::MagickSetImageResolution(self.wand, x_resolution, y_resolution)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -982,9 +920,7 @@ impl MagickWand {
/// Sets the wand resolution /// Sets the wand resolution
pub fn set_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> { pub fn set_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> {
match unsafe { match unsafe { bindings::MagickSetResolution(self.wand, x_resolution, y_resolution) } {
bindings::MagickSetResolution(self.wand, x_resolution, y_resolution)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1085,7 +1021,8 @@ impl MagickWand {
&self, &self,
width_scale: f64, width_scale: f64,
height_scale: f64, height_scale: f64,
filter: FilterType) -> Result<()> { filter: FilterType,
) -> Result<()> {
if width_scale < 0.0 { if width_scale < 0.0 {
return Err(MagickError("negative width scale given".to_string())); return Err(MagickError("negative width scale given".to_string()));
} }
@ -1106,9 +1043,7 @@ impl MagickWand {
/// 'thumbnail' optimizations which remove a lot of image meta-data with the goal /// 'thumbnail' optimizations which remove a lot of image meta-data with the goal
/// of producing small low cost images suited for display on the web. /// of producing small low cost images suited for display on the web.
pub fn thumbnail_image(&self, width: usize, height: usize) -> Result<()> { pub fn thumbnail_image(&self, width: usize, height: usize) -> Result<()> {
match unsafe { match unsafe { bindings::MagickThumbnailImage(self.wand, width.into(), height.into()) } {
bindings::MagickThumbnailImage(self.wand, width.into(), height.into())
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1218,9 +1153,7 @@ impl MagickWand {
/// ///
/// Returns `true` if successful or `false` if an error occurred. /// Returns `true` if successful or `false` if an error occurred.
pub fn auto_orient(&self) -> bool { pub fn auto_orient(&self) -> bool {
unsafe { unsafe { bindings::MagickAutoOrientImage(self.wand) == MagickTrue }
bindings::MagickAutoOrientImage(self.wand) == MagickTrue
}
} }
/// Write the current image to the provided path. /// Write the current image to the provided path.
@ -1309,28 +1242,16 @@ impl MagickWand {
/// ///
/// * `pixel_mask`: type of mask, Read or Write. /// * `pixel_mask`: type of mask, Read or Write.
/// * `clip_mask`: the clip_mask wand. /// * `clip_mask`: the clip_mask wand.
pub fn set_image_mask( pub fn set_image_mask(&mut self, pixel_mask: PixelMask, clip_mask: &MagickWand) -> Result<()> {
&mut self, match unsafe { bindings::MagickSetImageMask(self.wand, pixel_mask.into(), clip_mask.wand) }
pixel_mask: PixelMask, {
clip_mask: &MagickWand
) -> Result<()> {
match unsafe {
bindings::MagickSetImageMask(
self.wand,
pixel_mask.into(),
clip_mask.wand
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
} }
/// Set image channel mask /// Set image channel mask
pub fn set_image_channel_mask( pub fn set_image_channel_mask(&mut self, option: ChannelType) -> ChannelType {
&mut self,
option: ChannelType,
) -> ChannelType {
unsafe { bindings::MagickSetImageChannelMask(self.wand, option.into()).into() } unsafe { bindings::MagickSetImageChannelMask(self.wand, option.into()).into() }
} }
@ -1365,9 +1286,7 @@ impl MagickWand {
/// Simulate an image shadow /// Simulate an image shadow
pub fn shadow_image(&self, alpha: f64, sigma: f64, x: isize, y: isize) -> Result<()> { pub fn shadow_image(&self, alpha: f64, sigma: f64, x: isize, y: isize) -> Result<()> {
match unsafe { match unsafe { bindings::MagickShadowImage(self.wand, alpha, sigma, x, y) } {
bindings::MagickShadowImage(self.wand, alpha, sigma, x, y)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1471,14 +1390,18 @@ impl MagickWand {
colorspace: ColorspaceType, colorspace: ColorspaceType,
tree_depth: usize, tree_depth: usize,
dither_method: DitherMethod, dither_method: DitherMethod,
measure_error: bool) -> Result<()> { measure_error: bool,
match unsafe { bindings::MagickQuantizeImage( ) -> Result<()> {
match unsafe {
bindings::MagickQuantizeImage(
self.wand, self.wand,
number_of_colors.into(), number_of_colors.into(),
colorspace.into(), colorspace.into(),
tree_depth.into(), tree_depth.into(),
dither_method.into(), dither_method.into(),
measure_error.to_magick()) } { measure_error.to_magick(),
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1491,14 +1414,18 @@ impl MagickWand {
colorspace: ColorspaceType, colorspace: ColorspaceType,
tree_depth: usize, tree_depth: usize,
dither_method: DitherMethod, dither_method: DitherMethod,
measure_error: bool) -> Result<()> { measure_error: bool,
match unsafe { bindings::MagickQuantizeImages( ) -> Result<()> {
match unsafe {
bindings::MagickQuantizeImages(
self.wand, self.wand,
number_of_colors.into(), number_of_colors.into(),
colorspace.into(), colorspace.into(),
tree_depth.into(), tree_depth.into(),
dither_method.into(), dither_method.into(),
measure_error.to_magick()) } { measure_error.to_magick(),
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1529,19 +1456,10 @@ impl MagickWand {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub fn function_image( pub fn function_image(&self, function: MagickFunction, args: &[f64]) -> Result<()> {
&self,
function: MagickFunction,
args: &[f64]
) -> Result<()> {
let num_of_args: size_t = args.len().into(); let num_of_args: size_t = args.len().into();
match unsafe { match unsafe {
bindings::MagickFunctionImage( bindings::MagickFunctionImage(self.wand, function.into(), num_of_args, args.as_ptr())
self.wand,
function.into(),
num_of_args,
args.as_ptr()
)
} { } {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
@ -1557,13 +1475,7 @@ impl MagickWand {
return Err(MagickError("no constant coefficient given".to_string())); return Err(MagickError("no constant coefficient given".to_string()));
} }
let num_of_terms: size_t = (terms.len() >> 1).into(); let num_of_terms: size_t = (terms.len() >> 1).into();
match unsafe { match unsafe { bindings::MagickPolynomialImage(self.wand, num_of_terms, terms.as_ptr()) } {
bindings::MagickPolynomialImage(
self.wand,
num_of_terms,
terms.as_ptr()
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1573,12 +1485,7 @@ impl MagickWand {
/// ///
/// * `kernel_info`: An array of doubles representing the convolution kernel. /// * `kernel_info`: An array of doubles representing the convolution kernel.
pub fn convolve_image(&self, kernel_info: &KernelInfo) -> Result<()> { pub fn convolve_image(&self, kernel_info: &KernelInfo) -> Result<()> {
match unsafe { match unsafe { bindings::MagickConvolveImage(self.wand, kernel_info.get_ptr()) } {
bindings::MagickConvolveImage(
self.wand,
kernel_info.get_ptr()
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1593,14 +1500,14 @@ impl MagickWand {
&self, &self,
morphology_method: MorphologyMethod, morphology_method: MorphologyMethod,
iterations: isize, iterations: isize,
kernel_info: &KernelInfo kernel_info: &KernelInfo,
) -> Result<()> { ) -> Result<()> {
match unsafe { match unsafe {
bindings::MagickMorphologyImage( bindings::MagickMorphologyImage(
self.wand, self.wand,
morphology_method.into(), morphology_method.into(),
iterations.into(), iterations.into(),
kernel_info.get_ptr() kernel_info.get_ptr(),
) )
} { } {
MagickTrue => Ok(()), MagickTrue => Ok(()),
@ -1617,12 +1524,7 @@ impl MagickWand {
/// ///
/// * `color_matrix`: the color matrix. /// * `color_matrix`: the color matrix.
pub fn color_matrix_image(&self, color_matrix: &KernelInfo) -> Result<()> { pub fn color_matrix_image(&self, color_matrix: &KernelInfo) -> Result<()> {
match unsafe { match unsafe { bindings::MagickColorMatrixImage(self.wand, color_matrix.get_ptr()) } {
bindings::MagickColorMatrixImage(
self.wand,
color_matrix.get_ptr()
)
} {
MagickTrue => Ok(()), MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)), _ => Err(MagickError(self.get_exception()?.0)),
} }
@ -1640,19 +1542,15 @@ impl MagickWand {
/// ///
/// * `expression`: the expression. /// * `expression`: the expression.
pub fn channel_fx_image(&self, expression: &str) -> Result<MagickWand> { pub fn channel_fx_image(&self, expression: &str) -> Result<MagickWand> {
let c_expression = CString::new(expression).map_err(|_| "artifact string contains null byte")?; let c_expression =
CString::new(expression).map_err(|_| "artifact string contains null byte")?;
let result = unsafe { let result = unsafe { bindings::MagickChannelFxImage(self.wand, c_expression.as_ptr()) };
bindings::MagickChannelFxImage(
self.wand,
c_expression.as_ptr()
)
};
return if result.is_null() { return if result.is_null() {
Err(MagickError(self.get_exception()?.0)) Err(MagickError(self.get_exception()?.0))
} else { } else {
Ok(MagickWand{ wand: result }) Ok(MagickWand { wand: result })
}; };
} }
@ -1662,28 +1560,24 @@ impl MagickWand {
/// ///
/// * `colorspace`: the colorspace. /// * `colorspace`: the colorspace.
pub fn combine_images(&self, colorspace: ColorspaceType) -> Result<MagickWand> { pub fn combine_images(&self, colorspace: ColorspaceType) -> Result<MagickWand> {
let result = unsafe { let result = unsafe { bindings::MagickCombineImages(self.wand, colorspace.into()) };
bindings::MagickCombineImages(self.wand, colorspace.into())
};
return if result.is_null() { return if result.is_null() {
Err(MagickError(self.get_exception()?.0)) Err(MagickError(self.get_exception()?.0))
} else { } else {
Ok(MagickWand{ wand: result }) Ok(MagickWand { wand: result })
} };
} }
/// Returns the current image from the magick wand. /// Returns the current image from the magick wand.
pub fn get_image<'wand>(&'wand self) -> Result<Image<'wand>> { pub fn get_image<'wand>(&'wand self) -> Result<Image<'wand>> {
let result = unsafe { let result = unsafe { bindings::GetImageFromMagickWand(self.wand) };
bindings::GetImageFromMagickWand(self.wand)
};
return if result.is_null() { return if result.is_null() {
Err(MagickError(self.get_exception()?.0)) Err(MagickError(self.get_exception()?.0))
} else { } else {
unsafe { Ok(Image::new(result)) } unsafe { Ok(Image::new(result)) }
} };
} }
mutations!( mutations!(

View File

@ -23,5 +23,5 @@ pub use self::drawing::DrawingWand;
pub use self::magick::MagickWand; pub use self::magick::MagickWand;
pub use self::pixel::{PixelWand, HSL}; pub use self::pixel::{PixelWand, HSL};
use bindings::MagickBooleanType_MagickTrue as MagickTrue;
use bindings::MagickBooleanType_MagickFalse as MagickFalse; use bindings::MagickBooleanType_MagickFalse as MagickFalse;
use bindings::MagickBooleanType_MagickTrue as MagickTrue;

View File

@ -19,8 +19,8 @@ use std::fmt;
use bindings; use bindings;
use result::MagickError; use result::MagickError;
use crate::result::Result;
use super::MagickTrue; use super::MagickTrue;
use crate::result::Result;
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct HSL { pub struct HSL {

View File

@ -22,8 +22,8 @@ use std::io::Read;
use std::path::Path; use std::path::Path;
use std::sync::Once; use std::sync::Once;
use magick_rust::{magick_wand_genesis, MagickWand, PixelWand};
use magick_rust::MagickError; use magick_rust::MagickError;
use magick_rust::{magick_wand_genesis, MagickWand, PixelWand};
// Used to make sure MagickWand is initialized exactly once. Note that we // Used to make sure MagickWand is initialized exactly once. Note that we
// do not bother shutting down, we simply exit when the tests are done. // do not bother shutting down, we simply exit when the tests are done.
@ -54,7 +54,9 @@ fn test_resize_image() {
1 => 1, 1 => 1,
height => height / 2, height => height / 2,
}; };
assert!(wand.resize_image(halfwidth, halfheight, magick_rust::FilterType::Lanczos).is_ok()); assert!(wand
.resize_image(halfwidth, halfheight, magick_rust::FilterType::Lanczos)
.is_ok());
assert_eq!(256, wand.get_image_width()); assert_eq!(256, wand.get_image_width());
assert_eq!(192, wand.get_image_height()); assert_eq!(192, wand.get_image_height());
} }
@ -171,7 +173,10 @@ fn test_get_image_property() {
// retrieve a property that does not exist // retrieve a property that does not exist
let missing_value = wand.get_image_property("exif:Foobar"); let missing_value = wand.get_image_property("exif:Foobar");
assert!(missing_value.is_err()); assert!(missing_value.is_err());
assert_eq!(MagickError("missing property: exif:Foobar".to_string()), missing_value.unwrap_err()); assert_eq!(
MagickError("missing property: exif:Foobar".to_string()),
missing_value.unwrap_err()
);
} }
#[test] #[test]
@ -208,8 +213,7 @@ fn test_compare_images() {
assert!(wand2.read_image("tests/data/IMG_5745_rotl.JPG").is_ok()); assert!(wand2.read_image("tests/data/IMG_5745_rotl.JPG").is_ok());
wand2.auto_orient(); wand2.auto_orient();
let (distortion, diff) = let (distortion, diff) = wand1.compare_images(&wand2, magick_rust::MetricType::RootMeanSquared);
wand1.compare_images(&wand2, magick_rust::MetricType::RootMeanSquared);
assert!(distortion < 0.01); assert!(distortion < 0.01);
assert!(diff.is_some()); assert!(diff.is_some());
} }
@ -362,10 +366,7 @@ fn test_clut_image() {
assert!(gradient.read_image("gradient:black-yellow").is_ok()); assert!(gradient.read_image("gradient:black-yellow").is_ok());
assert!(wand assert!(wand
.clut_image( .clut_image(&gradient, magick_rust::PixelInterpolateMethod::Bilinear)
&gradient,
magick_rust::PixelInterpolateMethod::Bilinear
)
.is_ok()); .is_ok());
} }