HEIC图片转JPG

首先需要安装ImageMagick软件windows版下载链接,不同系统版本请参考此处。
使用示例:
convert_heic_to_jpg.py 下载后复制到HEIC文件所在的文件夹,空白处右键在终端中打开,执行以下cmd命令:

python .\convert_heic_to_jpg.py --input_dir . --output_dir . --quality 90 --remove_src True --max_workers 8

–input_dir :.当前目录,可替换为HEIC所在文件夹
–output_dir :.当前目录,可替换为转换后文件存储文件夹
–quality :90 设置转后质量90%
–remove_src :True 删除HEIC原文件,False 保留原文件
–max_workers :8 线程数量,使用者可根据设备资源自行修改

源码如下:

import argparse  
import os  
import subprocess  
import concurrent.futures 
  
def convert_heif_dir_to_jpeg(input_dir=".", output_dir=".", quality=90, remove_src=False):  
    """  
    批量转换HEIF文件到JPEG。  
  
    :param input_dir: 包含HEIF文件的目录。  
    :param output_dir: 存储转换后的JPEG文件的目录。  
    :param quality: JPEG图像的质量(1-100)。  
    """  
    # 确保输出目录存在  
    if not os.path.exists(output_dir):  
        os.makedirs(output_dir)  
    # 遍历输入目录中的所有HEIF文件  
    for filename in os.listdir(input_dir):  
        if filename.lower().endswith(('.heic', '.heif')):  
            # 构造输入和输出文件的完整路径  
            input_path = os.path.join(input_dir, filename)  
            base_name, _ = os.path.splitext(filename)  # 去除扩展名  
            output_path = os.path.join(output_dir, base_name + '.jpg')  
            # 获取绝对路径  
            # abs_input_path = os.path.abspath(input_path)  
            # abs_output_path = os.path.abspath(output_path)  
            # print(abs_output_path)  
              
            # ImageMagick 转换命令  
            command = ['magick', 'convert', abs_input_path, '-quality', str(quality), abs_output_path]  
              
            # 执行命令  
            try:  
                subprocess.run(command, check=True)  
                print("文件转换成功!")  
                  
                # 检查文件是否存在并尝试删除  
                if os.path.exists(abs_input_path) and remove_src is True:
                    os.system(f'del {abs_input_path}')  
                    print(f"已删除原文件:{abs_input_path}")  
                else:  
                    print(f"原文件不存在:{abs_input_path}")  
            except subprocess.CalledProcessError as e:  
                print(f"文件转换或删除失败:{e}")

def convert_heif_to_jpeg(input_file, output_dir=".", quality=90, remove_src=False):  
    """  
    批量转换HEIF文件到JPEG。  
  
    :param input_file: HEIF文件。  
    :param output_dir: 存储转换后的JPEG文件的目录。  
    :param quality: JPEG图像的质量(1-100)。  
    """  
    # 确保输出目录存在  
    if not os.path.exists(output_dir):  
        os.makedirs(output_dir)  
    # 遍历输入目录中的所有HEIF文件    
    if input_file.lower().endswith(('.heic', '.heif')):  
        # 构造输入和输出文件的完整路径   
        base_name, _ = os.path.splitext(input_file)  # 去除扩展名  
        output_path = os.path.join(output_dir, base_name + '.jpg')  
        # 获取绝对路径
        abs_input_path = os.path.abspath(input_file)  
        abs_output_path = os.path.abspath(output_path)  
        print(abs_output_path)  
          
        # ImageMagick 转换命令  
        command = ['magick', 'convert', abs_input_path, '-quality', str(quality), abs_output_path]  
          
        # 执行命令  
        try:  
            subprocess.run(command, check=True)  
            print("文件转换成功!")  
              
            # 检查文件是否存在并尝试删除  
            if os.path.exists(abs_input_path) and remove_src is True:
                os.system(f'del {abs_input_path}')  
                print(f"已删除原文件:{abs_input_path}")  
            else:  
                print(f"原文件不存在:{abs_input_path}")  
        except subprocess.CalledProcessError as e:  
            print(f"文件转换或删除失败:{e}")
  
def main():  
    # 创建命令行参数解析器  
    parser = argparse.ArgumentParser(description='Batch convert HEIF to JPEG using ImageMagick.')  
    parser.add_argument('--input_dir', type=str, default='.', help='Directory containing HEIF files, default is current directory.')  
    parser.add_argument('--output_dir', type=str, default='.', help='Directory to store converted JPEG files, default is current directory.')  
    parser.add_argument('--quality', type=int, default=90, help='JPEG quality (1-100), default is 90.')  
    parser.add_argument('--remove_src', type=bool, default=False, help='Remove *.HEIC source files after conversion, default is False.')  
    parser.add_argument('--max_workers', type=int, default=8, help='Max workers threads, default is 8.')  
    # 解析命令行参数  
    args = parser.parse_args()  
      
    # 获取输入目录下的所有HEIF文件  
    heif_files = [os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir) if f.lower().endswith('.heif') or f.lower().endswith('.heic')]  
      
    # 使用ThreadPoolExecutor来处理转换  
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.max_workers) as executor:  # 设置最大工作线程数  
        futures = []  
        for file in heif_files:
            future = executor.submit(convert_heif_to_jpeg, file, args.output_dir, args.quality, args.remove_src)  
            futures.append(future)  
  
        # 等待所有转换完成  
        concurrent.futures.wait(futures)  

        # 检查每个 Future 对象的状态  
        for future in futures:  
            if future.done():  
                print(f"Future {future} is done")  
                try:  
                    result = future.result()  # 如果函数有返回值,这里可以获取它  
                except Exception as e:  
                    print(f"Generated an exception: {e}")  
            else:  
                print(f"Future {future} is not done")

  
if __name__ == '__main__':  
    main()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/600601.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

JavaScript余数运算符

console.log(5 % 2); //5 2 * 2 1 console.log(8 % 3); //8 2 * 3 2 console.log(6 % 2); //6 2 * 3 0 console.log(7 % 2); //7 2 * 3 1● 我们可以利用这个特性来判断一个数是奇数还是偶数 const isEven n >n % 2 0 ? console.log(${n}是偶数) : console.…

Python扩展模块的开发

有关python C扩展开发的教程可以参考概述 — Python 3.12.3 文档。项目已经发布至python官方的pypi里了。具体详情请见AdroitFisherman PyPI。目前该项目还处在测试阶段。尚有部分模块需要开发和测试。 项目结构 项目结构见下图: 代码展示与说明 以单链表(SingleL…

【go项目01_学习记录04】

学习记录 1 集成 Gorilla Mux1.1 为什么不选择 HttpRouter?1.2 安装 gorilla/mux1.3 使用 gorilla/mux1.4 迁移到 Gorilla Mux1.4.1 新增 homeHandler1.4.2 指定 Methods () 来区分请求方法1.4.3 请求路径参数和正则匹配1.4.4 命名路由与链接生成 1 集成 Gorilla Mu…

【Linux网络】PXE批量网络装机

目录 一、系统装机 1.1 三种引导方式 1.2 系统安装过程 1.3 四大重要文件 二、PXE 2.1 PXE实现原理 2.2 PXE手动搭建过程 2.3 kickstart配合pxe完成批量自动安装 一、系统装机 1.1 三种引导方式 硬盘光驱(U盘)网络启动 1.2 系统安装过程 加载boot loader加载启动安…

借势母亲节h5小游戏的作用是什么

企业商家往往喜欢借势节日开展营销,母亲节作为5月的重要节日自然不可错过,不同行业商家都有自己开展互动想要实现的效果,如品牌宣传曝光、引流及渠道跳转等。 基于微信社交属性,有利于品牌发展,在【雨科】平台拥有多款…

SparkSQL优化

SparkSQL优化 优化说明 缓存数据到内存 Spark SQL可以通过调用spark.sqlContext.cacheTable("tableName") 或者dataFrame.cache(),将表用一种柱状格式( an inmemory columnar format)缓存至内存中。然后Spark SQL在执行查询任务…

有什么方便实用的成人口语外教软件?6个软件教你快速进行口语练习

有什么方便实用的成人口语外教软件?6个软件教你快速进行口语练习 口语能力在语言学习中占据着重要的位置,因为它直接关系到我们与他人进行交流和沟通的效果。为了提高口语能力,很多成人选择通过外教软件进行口语练习,这些软件提供…

【强训笔记】day13

NO.1 代码实现&#xff1a; #include <iostream>#include<string>using namespace std;int n,k,t; string s;int func() {int ret0;for(int i0;i<n;i){char chs[i];if(chL) ret-1;else{if(i-1>0&&i-2>0&&s[i-1]W&&s[i-2]W) retk…

基于Springboot 的 Excel表格的导入导出

首先 &#xff0c;引入相关依赖EasyPOI <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.4.0</version></dependency> 编写实体类&#xff1a; Data AllArgs…

Java 框架安全:Struts2 漏洞序列测试.

什么是 Struts2 框架 Struts 2 是一个用于创建企业级 Java 应用程序的开源框架。它是一个 MVC&#xff08;模型-视图-控制器&#xff09;框架&#xff0c;用于开发基于 Java EE&#xff08;Java Platform, Enterprise Edition&#xff09;的 Web 应用程序。Struts 2 主要解决…

ROS机器人实用技术与常见问题解决

问题速查手册&#xff08;时实更新&#xff09;更加全面丰富的问题手册记录 1.机器人使用GPARTED挂载未分配空间 需要在图型界面下操作&#xff0c;建议使用no machine连接 安装gparted磁盘分区工具, sudo apt-get install gparted -y 启动软件 sudo gparted 点击磁盘/内存…

C# OpenCvSharp 图片找茬

C# OpenCvSharp 图片找茬 目录 效果 项目 代码 下载 效果 项目 代码 using OpenCvSharp; using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace OpenCvSharp_Demo { public partial class Form1 : Form { …

1688快速获取整店铺列表 采集接口php Python

在电子商务的浪潮中&#xff0c;1688平台作为中国领先的批发交易平台&#xff0c;为广大商家提供了一个展示和销售商品的广阔舞台&#xff1b;然而&#xff0c;要在众多店铺中脱颖而出&#xff0c;快速获取商品列表并进行有效营销是关键。 竞争对手分析 价格比较&#xff1a;…

mysql5.7数据库安装及性能测试

mysql5.7数据库安装及性能测试 记录Centos7.9下安装mysql 5.7并利用benchmark工具简单测试mysql的性能。 测试机&#xff1a;centos7.9 配置&#xff1a;4C8G40G 1. 下安装mysql5.7 安装mysql5.7&#xff1a; # 通过官方镜像源安装$ wget http://dev.mysql.com/get/mysql57-com…

pandas索引

pandas索引 一、索引1.1 建立索引1.2 重置索引1.3 索引类型1.4 索引的属性1.5 索引的操作 一、索引 1.1 建立索引 建立索引可以在数据读取加载中指定索引&#xff1a; import pandas as pd df pd.read_excel(team.xlsx, index_colname) # 将name列设置为索引 df.head()效…

C语言 函数的定义与调用

上文 C语言 函数概述 我们对函数进行了概述 本文 我们来说函数的定义和调用 C语言规定 使用函数之前&#xff0c;首先要对函数进行定义。 根据模块化程序设计思想&#xff0c;C语言的函数定义是互相平行、独立的&#xff0c;即函数定义不能嵌套 C语言函数定义 分为三种 有参函…

Kansformer?变形金刚来自过去的新敌人

​1.前言 多层感知器(MLPs),也被称为全连接前馈神经网络,是当今深度学习模型的基础组成部分。 MLPs在机器学习中扮演着至关重要的角色,因为它们是用于近似非线性函数的默认模型,这得益于通用近似定理所保证的表达能力。然而,MLPs真的是我们能构建的最佳非线性回归器吗?尽管ML…

鸿蒙OpenHarmony南向:【Hi3516标准系统入门(命令行方式)】

Hi3516标准系统入门&#xff08;命令行方式&#xff09; 注意&#xff1a; 从3.2版本起&#xff0c;标准系统不再针对Hi3516DV300进行适配验证&#xff0c;建议您使用RK3568进行标准系统的设备开发。 如您仍然需要使用Hi3516DV300进行标准系统相关开发操作&#xff0c;则可能会…

人工智能编程的创新探索 卧龙与凤雏的畅想

在一间宽敞明亮的办公室内&#xff0c;阳光透过窗户洒在地上&#xff0c;形成一片片光斑。卧龙和凤雏正坐在舒适的办公椅上休息&#xff0c;享受着这片刻的宁静。 卧龙微微皱眉&#xff0c;一只手托着下巴&#xff0c;略显苦恼地说道&#xff1a;“现在的人工智能&#xff0c;也…

vue2人力资源项目5组织架构的增删改查

编辑表单回显 父组件&#xff1a;这里用到了父亲调子组件的方法和同步异步先后方法的处理 //methods里else if (type edit) {this.showDialog true// 显示弹层this.currentNodeId id// 记录id&#xff0c;要用它获取数据// 在子组件中获取数据// 父组件调用子组件的方法来获…
最新文章