AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78277451
Accepted
J. Martin
J. Martin
Asked: 2024-04-05 10:16:51 +0800 CST2024-04-05 10:16:51 +0800 CST 2024-04-05 10:16:51 +0800 CST

在 Rust 中编辑图像的不透明度

  • 772

我正在尝试循环遍历图像目录,将不透明度编辑为 50%,然后保存它们。我有一组 jpg 和 png 图像。我正在使用图像箱。

可能我必须对图像的格式进行一些考虑,但我不知道是什么......

use clap::Parser;
use std::{process, thread};
#[derive(Parser,Debug)]
#[command(author,version,about,long_about=None)]
struct Args {
    #[arg(long,value_hint=clap::ValueHint::DirPath, default_value="./")]
    picture_dir: std::path::PathBuf,
    #[arg(long, default_value="300")]
    draw_time: u64,
    #[arg(long, default_value="3")]
    start_delay: u64,
    #[arg(long)]
    dry_run: bool,
}


fn main() {
    let args = Args::parse();
    println!("{}", args.picture_dir.as_os_str().to_str().unwrap());
    let dir = args.picture_dir.as_os_str().to_str().unwrap();
    let dir = format!("{}/*.*", dir);
    let extensions_supported = vec!("png","jpg","bmp");
    for path in glob::glob(&dir).expect("Failed to list directory") {
        let path = path.unwrap();
        let copy_from_path = path.clone();
        let file_name = path.file_name().unwrap();
        let mut cachepath = std::env::temp_dir();
        cachepath.push(file_name.to_str().unwrap());
        let str_path = cachepath.to_str().unwrap();
        let path_extension = path.extension().unwrap().to_str().unwrap();
        if !extensions_supported.contains(&path_extension) {
            println!("We don't support that file type");
            continue;
        }
        println!("{}", str_path);
        let start = std::time::Instant::now();
        // We should open the program
        let cmd_str = format!("cmd.exe /C clipstudiopaint.exe {}", str_path);
        let mut child: Option<process::Child> = None;
        if args.dry_run {
            println!("{}",cmd_str);
        } else {
            std::fs::copy(copy_from_path,cachepath.clone()).expect("Failed to create temporary file");
            let cache_image_path = cachepath.clone();
            let cache_image_path = cache_image_path.to_str().unwrap();
            let save_image_path = cachepath.clone();
            let mut image = image::open(cache_image_path)
            .expect("Failed to open image for editing").to_rgba32f();
            image.pixels_mut().for_each(|p| p[3] /= 2.0);
            
            image.save(save_image_path.to_str().unwrap()).expect("Failed to save image");
            //let mut image_target = image::ImageBuffer::new(image.width(), image.height());
            child = Some(process::Command::new("cmd")
            .arg("/C")
            .arg("clipstudiopaint.exe")
            .arg(cachepath.to_str().unwrap())
            .spawn()
            .expect("Failed to run clipstudiopaint"));
        }
        // We should wait a couple of seconds for it to load
        loop {
            if start.elapsed().as_secs() > args.start_delay {
                break;
            }
        }
        let start = std::time::Instant::now();
        // we should wait the specified drawing time
        println!("Starting timer");
        loop {
            if start.elapsed().as_secs() > args.draw_time {
                break;
            }
        }   
        // we should kill the process
        if !args.dry_run {
            child.unwrap().kill().expect("Failed to kill childprocess");
            std::fs::remove_file(cachepath).expect("Failed to remove temp file");
        }
        let start = std::time::Instant::now();
        loop {
            if start.elapsed().as_secs() > 2 {
                break;
            }
        }  
    }
}

这会导致错误:Failed to save image: Encoding(EncodingError { format: Exact(Png), underlying: Some(ColorType(Rgba32F)) })

最终答案的相关部分最终如下所示:

std::fs::copy(copy_from_path,cachepath.clone()).expect("Failed to create temporary file");
let image_edit_path = image_edit_path.clone();
let image_edit_path = image_edit_path.to_str().unwrap();
let save_image_path = cachepath.clone();
println!("Opening: {} for editing", image_edit_path);
let mut image = image::open(image_edit_path)
.expect("Failed to open image for editing");
let mut target_image = image::DynamicImage::new_rgba8(image.width(), image.height());
let mut target_image = target_image.to_rgba8();
target_image.pixels_mut().for_each(|p| *p = image::Rgba{0: [246, 244, 237, 255]});
let mut image = image.to_rgba8();
image.pixels_mut().for_each(|p| p[3] = 100);
image::imageops::overlay(&mut target_image, &image, 0, 0);
let target_image = image::DynamicImage::ImageRgba8(target_image);

target_image.save(save_image_path.to_str().unwrap()).expect("Failed to save image");
image
  • 1 1 个回答
  • 27 Views

1 个回答

  • Voted
  1. Best Answer
    vallentin
    2024-04-05T10:27:30+08:002024-04-05T10:27:30+08:00

    并非所有编码器都支持所有颜色格式。

    由于您使用显式转换它to_rgba32f(),因此您同样必须将其转换回您正在使用的编码器支持的格式。对于 PNG,请使用例如to_rgba8()或into_rgba8()。

    let image = image.into_rgba8();
    
    image.save(...)...
    

    对于 JPEG,如果您想要透明度,您还必须将它们另存为(例如)PNG。

    否则,当您尝试保存它时,您同样会收到编码错误,因为 JPEG 不支持 Alpha 通道。(至少image板条箱编码器没有。)


    说得完全迂腐一点,JPEG 格式本身就支持“alpha”通道。image但这没有被使用,也没有得到广泛支持,而且crate也不支持它。请参阅Q2639866了解更多信息。

    • 1

相关问题

  • 如何在 Leptonica 中读取包含多页图像的 pdf

  • 广义霍夫变换中 Ballard 和 Guil 有什么区别?[关闭]

  • 重置/清除/取消选择选择框 javaFX

  • 想象库图像有黑色背景,将其设置为白色

  • Golang 为 jpeg 图像生成一致的哈希值,而无需写入磁盘

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve