Python を使用して、JPEG ファイルに埋め込まれた JFIF サムネイルを更新しようとしています。
これは、これを達成することになっている(少しハックな)方法です。
def set_thumbnail(self, data):
# Data of the updated thumbnail
data = bytearray(data)
# Get offset of the old thumbnail data
offset = (self._exif_start +
self._unpack('I', self._get_tag_offset(0x201)+8))
# Get size of the old thumbnail
old_size = self._unpack('I', self._get_tag_offset(0x202)+8)
try:
# Strip everything between the JFIF APP1 and the quant table
jfif_start = data.index('\xff\xe0')
quant_start = data.index('\xff\xdb')
stripped_data = data[0:jfif_start] + data[quant_start:]
except ValueError:
stripped_data = data
# Writes the new length to the buffer
self._pack('I', self._get_tag_offset(0x202)+8, len(stripped_data))
# Writes the new data to the image buffer
self._buf[offset:offset+old_size] = stripped_data
この関数は、古いサムネイルを書き直しても問題なく動作します。つまり、サムネイル データのサイズは変わりません。ただし、何らかの変換 (切り抜きや回転など) を適用して再度保存すると、結果のファイルは有効ではなくなったようです。
元の画像と、比較しやすいようにサムネイルを更新した画像の両方をアップロードしました。
identify
たとえば、次のようなエラーが表示されます。
identify.im6: Invalid JPEG file structure: two SOI markers `/tmp/thumb_rotated.jpg' @ error/jpeg.c/JPEGErrorHandler/316.
2 つの画像を比較すると、0x202
size タグの値は埋め込まれたサムネイル データのサイズと一致し、それに応じてファイルも大きくなります。