Cargo.toml
image = "0.23.12"
fltk = "0.10.14"
Run Code Online (Sandbox Code Playgroud)
我想使用 rust 的图像箱将 RGB 数据保存为 jpeg 文件:
use image::{RgbImage};
use image::ImageBuffer;
use fltk::{image::RgbImage, button::*};
let sourceImg = image::open("imgs/2.jpg").unwrap();
let rgb = RgbImage::new(&sourceImg.to_bytes(), x, y, 3).unwrap();
let mut prevWindowImgButton = Button::new(0,0, 300, 300, "");
prevWindowImgButton.set_image(Some(&rgb));
let rgbData= &prevWindowImgButton.image().unwrap().to_rgb_data();
//returns rgb data with type &Vec<u8>
rgbData.save("out/outputtest.jpg");
Run Code Online (Sandbox Code Playgroud)
给出错误:
testRGB.save("out/outputtest.jpg");
| ^^^^ method not found in `&Vec<u8>`
Run Code Online (Sandbox Code Playgroud)
因为 .save 必须在 ImageBuffer 上使用。那么如何将这个 rgb 数据转换为 ImageBuffer 呢?
如果您只想使用imagecrate 将原始缓冲区保存到图像文件,您可以使用以下save_buffer_with_format函数:
use image::io::Reader;
use image::save_buffer_with_format;
fn main() {
// The following three lines simply load a test image and convert it into buffer
let img = Reader::open("myimage.png").unwrap().decode().unwrap().to_rgb8();
let (width, height) = (img.width(), img.height());
let img_byte_vec = img.into_raw();
// The next line is what you want
save_buffer_with_format("myimg.jpg", &img_byte_vec, width, height, image::ColorType::Rgb8, image::ImageFormat::Jpeg).unwrap();
}
Run Code Online (Sandbox Code Playgroud)