Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

好久没更新博客了,其实并非是我的热情消失了,而是最近没有什么好写的,因为我在学用C语言实现一些东西,且水平低的令人羞于启齿,所以就没写了。
但是今天不一样了!额,今天有了新的需求,要我把几张图片从png格式转换成jpg格式。因为图片少,我也就没想用代码实现。但是手动拿PS转换的时候发现,速度真的是太低啦!emmm,也许是最近我又变懒了。。However,在手动转换完图片后,我又学习了一下用代码实现的方法,
我一共参考了两篇博客,其中一篇的url切换系统的时候弄丢了,所以只能贴出另一篇没有丢掉的博客链接了:OSError: cannot write mode RGBA as JPEG。顺便提一句,手机版CSDN分享链接时自动加的那一段话真的很烦人。

那么下面是代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
from PIL import Image

# 获取当前同级目录的文件列表
# get file list in this directory
img_list = os.listdir("./")
# 如果备份文件夹在这个文件夹下就跳过,如果没有备份文件夹就创建
# if the backup directory not in this directory, create it.
if (not (os.path.exists("./JPGSet"))):
os.mkdir("./JPGSet")

for name in img_list:
# 如果文件以png结尾
# if the file is end with png
if name.endswith(".png"):
try:
# 读取文件
# read the file
img = Image.open(name)
# 获取没有后缀名的文件名
# Get the file name without end name.
first_name = name[:name.rfind(".")]
# 将RGBA转换成RGB。A是Alpha,即透明度,JPG不支持透明度,所以如果不转换的话会报错
# change RGBA to RGB.The meaning of "A" is Alpha, if you don't change it to RGB, PIL will rise an Error.
img = img.convert('RGB')
# 保存图片到备份文件夹"JPGSet"下,其后缀名将会变成jpg
# save the pic to back up directory "JPGSet", it will end with jpg
img.save("./JPGSet/" + first_name + '.jpg', 'jpeg')
print(first_name + '.jpg', 'was saved at ./JPGSet.')

# 捕获无法读取的异常(因为代码我测试过了,可行,所以报IOError应该就是无法读取了)
# get the IOError.I tested the code, at my computer, it could be run.So if there is some reason to make IOError raise, maybe the file is not a picture or you don't have enough permission.
except IOError:
print("This file made IOError:", name)

else:
continue

这次的注释非常全,因为我打算发到github上…所以我就不解释了。着急睡觉了。
那么,本篇博客完~

评论



愿火焰指引你