use crate::{ImageXObject, Mm, PdfLayerReference, Px};
#[cfg(feature = "embedded_images")]
use image_crate::{self, DynamicImage, ImageDecoder};
#[derive(Debug)]
pub struct Image {
pub image: ImageXObject,
}
impl From<ImageXObject> for Image {
fn from(image: ImageXObject) -> Self {
Self { image }
}
}
#[cfg(feature = "embedded_images")]
impl<'a> Image {
pub fn try_from<T: ImageDecoder<'a>>(image: T) -> Result<Self, image_crate::ImageError> {
let image = ImageXObject::try_from(image)?;
Ok(Self { image })
}
pub fn from_dynamic_image(image: &DynamicImage) -> Self {
Self {
image: ImageXObject::from_dynamic_image(image),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ImageTransform {
pub translate_x: Option<Mm>,
pub translate_y: Option<Mm>,
pub rotate: Option<ImageRotation>,
pub scale_x: Option<f32>,
pub scale_y: Option<f32>,
pub dpi: Option<f32>,
}
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ImageRotation {
pub angle_ccw_degrees: f32,
pub rotation_center_x: Px,
pub rotation_center_y: Px,
}
impl Image {
pub fn add_to_layer(self, layer: PdfLayerReference, transform: ImageTransform) {
use crate::CurTransMat;
use crate::Pt;
let dpi = transform.dpi.unwrap_or(300.0);
let image_w = self.image.width.into_pt(dpi);
let image_h = self.image.height.into_pt(dpi);
let image = layer.add_image(self.image);
let scale_x = transform.scale_x.unwrap_or(1.0);
let scale_y = transform.scale_y.unwrap_or(1.0);
let image_w = image_w.0 * scale_x;
let image_h = image_h.0 * scale_y;
let mut transforms = Vec::new();
transforms.push(CurTransMat::Scale(image_w, image_h));
if let Some(rotate) = transform.rotate.as_ref() {
transforms.push(CurTransMat::Translate(
Pt(-rotate.rotation_center_x.into_pt(dpi).0),
Pt(-rotate.rotation_center_y.into_pt(dpi).0),
));
transforms.push(CurTransMat::Rotate(rotate.angle_ccw_degrees));
transforms.push(CurTransMat::Translate(
rotate.rotation_center_x.into_pt(dpi),
rotate.rotation_center_y.into_pt(dpi),
));
}
if transform.translate_x.is_some() || transform.translate_y.is_some() {
transforms.push(CurTransMat::Translate(
transform.translate_x.unwrap_or(Mm(0.0)).into_pt(),
transform.translate_y.unwrap_or(Mm(0.0)).into_pt(),
));
}
layer.use_xobject(image, &transforms);
}
}