使用 Docker 容器来批量转换 HEIC 文件到 PNG 文件
编辑日期: 2024-07-22 文章阅读: 次
使用 Docker 容器来批量转换 HEIC 文件到 PNG 文件。 这样不仅解决了依赖问题,还确保了环境的一致性。
总结
你使用了以下步骤:
- 创建 Dockerfile:定义了一个 Dockerfile,安装了所需的依赖项和 Python 包。
- 创建转换脚本:编写了
heic_to_png.py
脚本,用于将 HEIC 文件转换为 PNG 文件。 - 构建 Docker 镜像:使用
docker build
命令构建了 Docker 镜像。 - 运行 Docker 容器:使用
docker run
命令运行 Docker 容器,并挂载了输入和输出目录,成功完成了文件转换。
示例代码回顾
Dockerfile:
FROM python:3.9-slim
RUN apt-get update && apt-get install -y \
libheif-dev \
build-essential \
&& rm -rf /var/lib/apt/lists/*
RUN pip install pillow-heif pillow
COPY heic_to_png.py /heic_to_png.py
ENTRYPOINT ["python", "/heic_to_png.py"]
heic_to_png.py:
import os
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener()
def heic_to_png(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith('.heic'):
heic_path = os.path.join(input_dir, filename)
png_filename = os.path.splitext(filename)[0] + '.png'
png_path = os.path.join(output_dir, png_filename)
image = Image.open(heic_path)
image.save(png_path, "PNG")
print(f'Converted {filename} to {png_filename}')
input_directory = '/input'
output_directory = '/output'
heic_to_png(input_directory, output_directory)
使用命令
构建 Docker 镜像:
docker build -t heic_to_png .
运行 Docker 容器:
docker run --rm -v /Users/zhenguo/Documents/slu/projects/2trojan/trojan-CL2/store/trigger_images_hiformat:/input -v /Users/zhenguo/Documents/slu/projects/2trojan/trojan-CL2/store/trigger_images:/output heic_to_png