rust将bitmap位图文件另存为png格式的方法
更新时间:2024年03月28日 10:59:20 作者:会编程的大白熊
通过添加依赖,转换函数和单元测试操作步骤来解决将bitmap位图文件另存为png格式文件,本文通过实例代码给大家介绍的非常详细,对rust bitmap位另存为png格式的操作方法感兴趣的朋友一起看看吧
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud)
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
本文提供了一种将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初体验:手把手教你构建‘Hello,?World!’
"准备好了吗?一起踏上Rust编程语言的精彩旅程!在这篇「Rust初体验」中,我们将手把手教你构建经典程序“Hello,?World!”,感受Rust的强大与安全,短短几行代码,就能让你对这个系统级语言的魅力一探究竟!快加入吧,惊喜等你发现!"2024-01-01
最新评论