rust - 将bitmap位图文件另存为png格式

本文介绍了如何使用Cargo和imagecrate在Rust中实现将位图(BMP)文件转换为PNG格式,并提供了单元测试示例。
摘要由CSDN通过智能技术生成

本文提供了一种将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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值