插入缩略图代码如下:
import cv2
import piexif
import numpy as np
import io# 读取原图图像
original_image = cv2.imread("1.jpg")
retval, orgimg_buffer = cv2.imencode('.jpg', original_image)
# 读取EXIF数据
exif_dict = piexif.load(orgimg_buffer.tobytes())
# 读取Thumbnail图像
new_thumbnail_image = cv2.imread("thumbnail.jpg", cv2.IMREAD_GRAYSCALE)
# 在内存中转换为JPEG格式
retval, thumbnail_buffer = cv2.imencode('.jpg', new_thumbnail_image)
# 将缩略图插入到JPG中
exif_dict["thumbnail"] = thumbnail_buffer.tobytes()
exif_bytes = piexif.dump(exif_dict)# 修改orgimg_buffer的EXIF部分为exif_dict
decoded_image = cv2.imdecode(np.frombuffer(orgimg_buffer, dtype=np.uint8), cv2.IMREAD_COLOR)
image_bytes = cv2.imencode('.jpg', decoded_image)[1].tobytes()
output_file = io.BytesIO()
piexif.insert(exif_bytes, image_bytes, output_file)
# 将修改后的JPG数据保存到新的文件
with open("output.jpg", "wb") as f:f.write(output_file.getvalue())
提取缩略图:
import cv2
import piexif
import numpy as npdef extract_and_save_thumbnail(input_file, output_file):# 读取JPEG文件with open(input_file, 'rb') as f:jpeg_data = f.read()# 加载EXIF数据exif_dict = piexif.load(jpeg_data)# 检查是否存在Thumbnailif 'thumbnail' in exif_dict:thumbnail_data = exif_dict['thumbnail']# 将Thumbnail数据转换为图像thumbnail_array = np.frombuffer(thumbnail_data, dtype=np.uint8)thumbnail_image = cv2.imdecode(thumbnail_array, cv2.IMREAD_UNCHANGED)# 保存Thumbnail图像cv2.imwrite(output_file, thumbnail_image)print(f"Thumbnail saved to {output_file}")else:print("EXIF中没有找到缩略图字段")# 使用示例
extract_and_save_thumbnail("test.jpg", "thumbnail.jpg")