rust将bitmap位图文件另存为png格式的方法
更新时间:2024年03月28日 10:59:20 作者:会编程的大白熊
通过添加依赖,转换函数和单元测试操作步骤来解决将bitmap位图文件另存为png格式文件,本文通过实例代码给大家介绍的非常详细,对rust bitmap位另存为png格式的操作方法感兴趣的朋友一起看看吧
本文提供了一种将bitmap位图文件另存为png格式文件的方法。
添加依赖
cargo add image
转换函数
use image::{
codecs::png::PngEncoder, GenericImageView, ImageEncoder, ImageFormat,
ImageResult,
};
use std::{
fs,
io::{BufReader, BufWriter},
path::Path,
};
/// 将bitmap位图转换为png格式
pub fn to_png(bitmap_path: &Path, png_path: &Path) -> ImageResult<()> {
// 读取位图文件
let bitmap_fs = fs::File::open(bitmap_path).expect("Read bitmap");
let buf_reader = BufReader::new(bitmap_fs);
let img = image::load(buf_reader, ImageFormat::Bmp).unwrap();
// 创建png空文件
let png_file = fs::File::create(png_path)?;
let ref mut buff = BufWriter::new(png_file);
let encoder = PngEncoder::new(buff);
// 转换并写png文件
encoder.write_image(
&img.as_bytes().to_vec(),
img.dimensions().0,
img.dimensions().1,
img.color().into(),
)
}单元测试
use core_utils::image::bitmap;
use std::env;
#[test]
fn test_to_png() {
// 读取bitmpa文件
let bitmap_path = env::current_dir().unwrap().join("tests/test-image.bmp");
// 保存png文件
let png_path = env::current_dir().unwrap().join("tests/test-image.png");
bitmap::to_png(bitmap_path.as_path(), png_path.as_path()).unwrap();
}到此这篇关于rust如何将bitmap位图文件另存为png格式的文章就介绍到这了,更多相关rust bitmap位另存为png格式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
相关文章
Rust语言从入门到精通系列之Iterator迭代器深入详解
这篇文章主要为大家介绍了Rust语言从入门到精通系列之Iterator迭代器深入详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04


最新评论