简体   繁体   English

转换&amp;Vec<u8> RGB 数据到 ImageBuffer Rust</u8>

[英]Convert &Vec<u8> RGB Data to ImageBuffer Rust

Cargo.toml货运.toml

image = "0.23.12"
fltk = "0.10.14"

I'd like to save a rgb data as a jpeg file using rust's image crate:我想使用 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");

Gives error:给出错误:

    testRGB.save("out/outputtest.jpg");
    |                         ^^^^ method not found in `&Vec<u8>`

Because.save must be used on an ImageBuffer.因为.save 必须在 ImageBuffer 上使用。 So how do I convert this rgb data to an ImageBuffer?那么如何将此 rgb 数据转换为 ImageBuffer 呢?

If all you want is to save a raw buffer to image file using the image crate you can use the save_buffer_with_format func:如果您只想使用image箱将原始缓冲区保存到图像文件,您可以使用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();
}

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

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