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();
}

相关推荐

  1. rust - bitmap文件png格式

    2024-03-24 23:26:04       18 阅读
  2. 用PythonWord文件任意支持的格式

    2024-03-24 23:26:04       12 阅读
  3. rust - windows剪贴板的截保存png

    2024-03-24 23:26:04       17 阅读
  4. 【EXCEL自动化08】xls文件批量xlsx文件

    2024-03-24 23:26:04       20 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 23:26:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 23:26:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 23:26:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 23:26:04       20 阅读

热门阅读

  1. PostgreSQL与MySQL对比

    2024-03-24 23:26:04       19 阅读
  2. jvm底层

    jvm底层

    2024-03-24 23:26:04      15 阅读
  3. python

    2024-03-24 23:26:04       17 阅读
  4. 【机器学习-09】特征工程

    2024-03-24 23:26:04       16 阅读
  5. js和jsp的区别

    2024-03-24 23:26:04       16 阅读
  6. 组织碳管理--常见问题解答FAQ

    2024-03-24 23:26:04       19 阅读
  7. 【LeetCode-45.跳跃游戏】

    2024-03-24 23:26:04       15 阅读
  8. react native 总结

    2024-03-24 23:26:04       20 阅读
  9. C++面向对象:智能指针讲解

    2024-03-24 23:26:04       18 阅读
  10. 普通用户无法连接到docker服务

    2024-03-24 23:26:04       15 阅读
  11. C++:可变参数实现日志系统

    2024-03-24 23:26:04       22 阅读