简体   繁体   English

如何转换 Clamped <vec<u8> &gt; 用 Rust 和 web-sys 夹紧&lt;&amp;mut [u8]&gt;? </vec<u8>

[英]How do I convert Clamped<Vec<u8>> to Clamped<&mut [u8]> with Rust and web-sys?

I am manipulating pixel data using Rust and WebAssembly, and am struggling to create new ImageData with the manipulated pixels.我正在使用 Rust 和 WebAssembly 操作像素数据,并且正在努力使用操作的像素创建新的 ImageData。

When I get my ImageData 's data, it returns a Clamped<Vec<u8>>当我获得ImageData的数据时,它返回一个Clamped<Vec<u8>>

   fn get_buffer_image_data(&self) -> Clamped<Vec<u8>> {
    let image_data = match self.buffer_ctx.get_image_data(0.0, 0.0, 640.0, 480.0) {
        Ok(d) => d,
        Err(_err) => panic!("failed to fetch buffer image data")
    };
    
    image_data.data()
}

I manipulate the pixel data in another function, and then attempt to create new ImageData with these manipulated pixels.我在另一个 function 中操作像素数据,然后尝试使用这些操作像素创建新的 ImageData。 The problem is that I can only create new ImageData with Clamped<&mut [u8]>问题是我只能用Clamped<&mut [u8]>创建新的 ImageData

    fn create_image_data(&self, data: Clamped<Vec<u8>>) {
        let imageData = ImageData::new_with_u8_clamped_array_and_sh(data, 640, 480);
    }

However, the error I receive is:但是,我收到的错误是:

mismatched types

expected `&mut [u8]`, found struct `std::vec::Vec`

note: expected struct `wasm_bindgen::Clamped<&mut [u8]>`
         found struct `wasm_bindgen::Clamped<std::vec::Vec<u8>>`

I think I need to convert one type to another.我想我需要将一种类型转换为另一种。 How do I convert efficiently?如何高效转换? I have been trying this for a while and I am stuck.我已经尝试了一段时间,但我被卡住了。 The only solution I have is to send the entire Uint8ClampedArray to wasm from my JS.我唯一的解决方案是将整个 Uint8ClampedArray 从我的 JS 发送到 wasm。 Here is a code example you can use.这是您可以使用的代码示例。 Note, if you clone this repo please checkout the branch problem https://github.com/Fallenstedt/rotated-pixels/blob/problem/src/pixel_rotator.rs#L42-L44注意,如果你克隆这个 repo,请检查分支problem https://github.com/Fallenstedt/rotated-pixels/blob/problem/src/pixel_rotator.rs#L42-L44

If you look at the source code for Clamped , you'll see that it is just a wrapper around T .如果您查看Clamped的源代码,您会发现它只是T的包装器。

pub struct Clamped<T>(pub T);

Because the inner T is public, you can perform any operations on it, such as converting a Vec to a slice:因为内部T是公共的,所以可以对其执行任何操作,例如将Vec转换为切片:

let slice_data: &mut [u8] = &mut data.0[..];

You can then wrap slice_data in a new instance of Clamped , and pass it to ImageData :然后,您可以将slice_data包装在Clamped的新实例中,并将其传递给ImageData

fn create_image_data(&self, data: Clamped<Vec<u8>>) {
  let slice_data = Clamped(&mut data.0[..]);
  let imageData = ImageData::new_with_u8_clamped_array_and_sh(slice_data, 640, 480);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM