rust將bitmap位圖文件另存為png格式的方法
更新時(shí)間:2024年03月28日 10:59:20 作者:會(huì)編程的大白熊
通過添加依賴,轉(zhuǎn)換函數(shù)和單元測試操作步驟來解決將bitmap位圖文件另存為png格式文件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對rust bitmap位另存為png格式的操作方法感興趣的朋友一起看看吧
本文提供了一種將bitmap位圖文件另存為png格式文件的方法。
添加依賴
cargo add image
轉(zhuǎn)換函數(shù)
use image::{ codecs::png::PngEncoder, GenericImageView, ImageEncoder, ImageFormat, ImageResult, }; use std::{ fs, io::{BufReader, BufWriter}, path::Path, }; /// 將bitmap位圖轉(zhuǎn)換為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(); // 創(chuàng)建png空文件 let png_file = fs::File::create(png_path)?; let ref mut buff = BufWriter::new(png_file); let encoder = PngEncoder::new(buff); // 轉(zhuǎn)換并寫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(); }
到此這篇關(guān)于rust如何將bitmap位圖文件另存為png格式的文章就介紹到這了,更多相關(guān)rust bitmap位另存為png格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
rust多個(gè)mod文件引用和文件夾mod使用注意事項(xiàng)小結(jié)
在 Rust 項(xiàng)目中,可以使用 mod 關(guān)鍵字將一個(gè)文件夾或一個(gè) rs 文件作為一個(gè)模塊引入到當(dāng)前文件中,本文給大家介紹rust多個(gè)mod文件引用和文件夾mod使用注意事項(xiàng)小結(jié),感興趣的朋友跟隨小編一起看看吧2024-03-03Rust語言從入門到精通系列之Iterator迭代器深入詳解
這篇文章主要為大家介紹了Rust語言從入門到精通系列之Iterator迭代器深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04