当前位置: 首页 > article >正文

使用Python编辑JPEG文件EXIF字段中的缩略图

插入缩略图代码如下:

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 np

def 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)
    
    # 检查是否存在Thumbnail
    if '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")


http://www.kler.cn/a/445154.html

相关文章:

  • 生态:React Native
  • ava:186 基于SSM的旅游攻略管理系统
  • git使用和gitlab部署
  • 【前端】NodeJS:MongoDB
  • 【小白你好】深度学习的认识和应用:CNN、GNN、LSTM、Transformer、GAN与DRL的对比分析
  • 《Qt Creator 4.11.1 教程》
  • 公共建筑智慧用电火灾预防监测系统介绍
  • 第二十四天 循环神经网络(RNN)LSTM与GRU
  • 解决npm publish发布包后拉取时一直提示 Couldn‘t find any versions for “包名“ that matches “版本号“
  • 启动报错java.lang.NoClassDefFoundError: ch/qos/logback/core/status/WarnStatus
  • 同源策略:为什么XMLHttpRequest不能跨域请求资源?
  • 现代风格VUE3易支付用户控制中心
  • 数据结构之二叉搜索树(Binary Search Tree)
  • VSCode编辑+GCC for ARM交叉编译工具链+CMake构建+OpenOCD调试(基于STM32的标准库/HAL库)
  • [图] 遍历 | BFS | DFS
  • 使用 UniApp 在微信小程序中实现 SSE 流式响应
  • vue-office:Star 4.2k,款支持多种Office文件预览的Vue组件库,一站式Office文件预览方案,真心不错
  • 探索国产数字隔离器——测试与应用
  • MariaDB 设置 sql_mode=Oracle 和 Oracle 对比验证
  • Vue3 的 Teleport 是什么?在什么场景下会用到?