> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Rust OpenCV编码图像并转换为Base64格式
- URL: https://yinguobing.com/blog/rust-opencv-image-encoding-base64/
- Published: 2022-07-11T14:49:29.000Z
- Updated: 2026-09-08T02:07:20.000Z
- Description: 如何在Rust下使用OpenCV编码图像
- Author: 尹国冰
- Tags: Rust, OpenCV

这篇文章展示了如何在Rust下使用OpenCV读取图像、编码为jpg格式并将编码后的图像文件再次编码为Base64格式的过程。

照惯例先上代码：

```rust
use base64::encode;
use opencv::imgcodecs;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // 读取图像
    let img = imgcodecs::imread("input.jpg", imgcodecs::IMREAD_ANYCOLOR)?;

    // 编码图像所需要的参数对象，这里为默认值。
    let params: opencv::core::Vector<i32> = opencv::core::Vector::new();

    // 用于存储编码后图像的buffer
    let mut buf: opencv::core::Vector<u8> = opencv::core::Vector::new();

    // 编码该图像为jpg格式
    let result = imgcodecs::imencode(".jpg", &img, &mut buf, &params)?;
    
    // 将图像文件编码为base64格式
    let img_b64 = encode(buf);

    // Main函数需要返回数值
    Ok(())
}
```

💡

这段代码涉及到了两个crate: base64与opencv。

图像编码函数的定义为：

```rust
pub fn imencode(ext: &str, img: &dyn core::ToInputArray, buf: &mut core::Vector<u8>, params: &core::Vector<i32>) -> Result<bool>
```

与之前图像存储函数类似，图像编码函数需要显式指定两个参数： `buf` 与 `params` 。这里的 `buf` 类型为 `opencv::core::Vector<u8>` ，顾名思义，用来存储编码以后的图像文件。 `params` 类型为 `opencv::core::Vector<i32>` ，内容为编码规格的具体参数。默认参数可以使用 `opencv::core::Vector::new()` 来构建。

编码成功后，即可使用 `base64` 的 `encode` 方法来编码。该方法返回的数据类型为 `String` 。