Skip to main content

dxcapture/capture/
img.rs

1use image::{
2    DynamicImage,
3    ImageBuffer,
4    RgbaImage,
5    Bgra,
6};
7
8use super::*;
9
10#[derive(Clone, Debug, Default)]
11/// this is container for image.
12/// 
13/// [Read more](`Capture::get_img_frame`)
14#[cfg_attr(feature = "docs-features", doc(cfg(feature = "img")))]
15pub struct ImgFrameData {
16    pub width: i32,
17    pub height: i32,
18    pub data: RgbaImage,
19}
20impl ImgFrameData {
21    pub fn new(width: i32, height: i32, data: RgbaImage) -> Self {
22        Self{
23            width, height, data
24        }
25    }
26}
27
28impl Capture {
29    /// Get image RgbaImage from a Direct3D surface
30    /// 
31    /// for [image] crate.
32    /// 
33    /// Required features: *`"img"`*
34    /// # Examples
35    /// ```
36    /// let device = dxcapture::Device::default();
37    /// let capture = dxcapture::Capture::new(&device).unwrap();
38    /// 
39    /// let image = capture.wait_img_frame().expect("Failed to capture");
40    /// let path = "image.png";
41    /// 
42    /// image.data.save(path).expect("Failed to save");
43    /// ```
44    pub fn get_img_frame(&self) -> anyhow::Result<ImgFrameData, CaptureError> {
45        let raw = self.get_raw_frame()?;
46
47        let image: ImageBuffer<Bgra<u8>, _> =
48            ImageBuffer::from_raw(raw.width as u32, raw.height as u32, raw.data).unwrap();
49        let dynamic_image = DynamicImage::ImageBgra8(image);
50        let dynamic_image = dynamic_image.to_rgba8();
51
52        Ok(ImgFrameData::new( raw.width as i32, raw.height as i32, dynamic_image ))
53    }
54
55    /// Get opencv image from a Direct3D surface. with throught NoTexture
56    pub fn wait_img_frame(&self) -> anyhow::Result<ImgFrameData, CaptureError> {
57        loop {
58            match self.get_img_frame() {
59                Ok(mat) => return Ok(mat),
60                Err(e) => {
61                    if e == CaptureError::NoTexture {
62                        continue;
63                    }
64                    return Err(e);
65                },
66            }
67        }
68    }
69}