cargo 图片转base64 完整可以运行的代码

要将图片转换为Base64编码,可以使用Rust语言和imagebase64等库。以下是一个完整的可以运行的代码示例,使用Cargo来管理依赖。

 

步骤

 

  1. 创建一个新的Cargo项目:

 

sh
 
Copy
cargo new image_to_base64
cd image_to_base64

 

  1. 添加依赖:在Cargo.toml文件中添加需要的库。

 

toml
 
Copy
[dependencies]
image = "0.23"
base64 = "0.13"
reqwest = { version = "0.11", features = ["blocking"] }

 

  1. 编写代码:在src/main.rs文件中编写如下代码:

 

rust
 
Copy
use std::fs::File;
use std::io::Read;
use base64::encode;

fn main() {
    // 读取图片文件
    let img_path = "path/to/your/image.png"; // 替换为你的图片路径
    let mut file = File::open(img_path).expect("Failed to open image file");

    // 读取文件内容到字节向量
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer).expect("Failed to read image file");

    // 将字节向量编码为Base64
    let encoded = encode(&buffer);

    println!("Base64 Encoded Image:\n{}", encoded);
}

 

运行代码

 

  1. 将你的图片放在项目目录中,并更新代码中的路径:

 

rust
 
Copy
let img_path = "path/to/your/image.png"; // 替换为你的图片路径

 

  1. 编译并运行:

 

sh
 
Copy
cargo run

 

输出

 

程序将输出Base64编码后的图片数据。

 

完整项目结构

 

plaintext
 
Copy
image_to_base64
├── Cargo.toml
└── src
    └── main.rs

 

确保你已经安装了Rust和Cargo,并且在项目根目录下运行cargo run。这样,你就可以将图片转换为Base64编码并在终端中输出了。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
编写代码:在src/main.rs文件中编写如下代码:

rust
 
Copy
use reqwest::blocking::get;
use base64::encode;
use std::io::Read;

fn main() {
    // 网络图片URL
    let img_url = "https://example.com/path/to/your/image.png"; // 替换为你的图片URL

    // 下载图片
    let mut response = get(img_url).expect("Failed to download image");
    let mut buffer = Vec::new();
    response.read_to_end(&mut buffer).expect("Failed to read image");

    // 将字节向量编码为Base64
    let encoded = encode(&buffer);

    println!("Base64 Encoded Image:\n{}", encoded);
}

运行代码


  1. 更新代码中的图片URL:

rust
 
Copy
let img_url = "https://example.com/path/to/your/image.png"; // 替换为你的图片URL

  1. 编译并运行:

sh
 
Copy
cargo run

输出


程序将输出Base64编码后的图片数据。

完整项目结构


plaintext
 
Copy
image_to_base64
├── Cargo.toml
└── src
    └── main.rs
posted @ 2024-07-10 17:25  易先讯  阅读(6)  评论(0编辑  收藏  举报