据我所知,JPEG文件有
几种不同的类型。这里解释了更改JFIF类型DPI元数据所需的详细信息
(点击此处)。基于此,我编写了自己的Python脚本,可以在不重新编码的情况下更改
JFIF类型 JPEG的DPI设置:
import sys,os
filename = sys.argv[1]
x_density = int(sys.argv[2])
y_density = int(sys.argv[3])
echo = True
if len(sys.argv) > 4:
if sys.argv[4] == 'quiet':
echo = False
assert x_density > 0 and x_density < 65536
assert y_density > 0 and y_density < 65536
APP0 = bytes.fromhex('FFD8FFE0')
APP1 = bytes.fromhex('FFD8FFE1')
with open(filename, 'rb+') as f:
chunk = f.read(4)
if chunk == APP0:
f.seek(2,1)
chunk = f.read(5)
if chunk == bytes.fromhex('4A46494600'):
f.seek(2,1)
print('Setting density of ' + os.path.split(filename)[1] + ' to ' + str(x_density) + 'x' + str(y_density) + ' dpi.') if echo else None
f.write(bytes.fromhex('01'))
f.write(x_density.to_bytes(2,'big'))
f.write(y_density.to_bytes(2,'big'))
else:
print('File hasn''t got the JFIF indentifier, nothing was done.')
elif chunk == APP1:
f.close()
print('This is an EXIF-JPEG, using exiftool to set DPI...')
os.system('exiftool -P -overwrite_original -XResolution={} -YResolution={} "{}"'.format(x_density,y_density,filename))
else:
print('File is not JFIF nor EXIF, cannot set DPI, nothing was done.')
print('Done.') if echo else None
使用方法:
python this_script.py some-image.jpg Xdpi Ydpi [quiet]
这个脚本并不读取完整的图像,也不改变文件长度,它只是直接修改JPEG文件上的一些字节。
此外,由于我希望脚本能够在硬链接文件上运行,所以没有创建临时/备份副本,因此整个过程对于JFIF JPEG来说非常快。
该脚本能够识别EXIF JPEG并使用exiftool来更改DPI。如果您的计算机上没有安装exiftool,请记得相应地调整脚本。即使您已经安装了exiftool,使用这个脚本的一个原因是速度;在我的测试中,这个脚本比exiftool要快得多。
JFIF和EXIF是JPEG文件最常见的类型,但我希望有人能够改进这个脚本或报告一种设置DPI(无需重新编码)的方法,也适用于带有APP14标记的Adobe JPEG,这种类型并不少见。
magick identify -verbose image.jpg
检查输入和输出。还要注意,在Imagemagick 7中,仅使用magick,而不是magick convert或convert。 - fmw42@mmj
- fmw42