python小工具_圖片格式HEIC轉JPG

python小工具_圖片格式HEIC轉JPG的圖1
python小工具_圖片格式HEIC轉JPG的圖2
python小工具_圖片格式HEIC轉JPG的圖3
注意pip install 時別掛VPN;
HEIF 包不支持windows, 這個pillow_heif可以。

python3.8沒成功,不知什么原因。3.9成功了。

蘋果手機拍照選擇小尺寸節省容量,就會保存有HEIC格式圖片,有的電腦無法直接查看,需要安裝額外的軟件。我們也可以用python轉一下格式。

# -*- coding: utf-8 -*-
from PIL import Image
# import pyheif   #不支持windows系統
import os
import pillow_heif
import whatimage


# 循環讀取HEIC格式照片,寫入JPG
def recyle_convert( org_path, dst_path):
    # 若是目錄,將org_path 改為其下文件path
    if os. path. isdir( org_path):
        file_list = os. listdir( org_path)
        for idx, file in enumerate( file_list):
            sub_path = os. path. join( org_path, file)
            recyle_convert( sub_path, dst_path)
    # 若是文件,轉換
    elif os. path. isfile( org_path):
        with open( org_path, 'rb') as f:
            file_data = f. read()
            try:
                # 判斷照片格式
                fmt = whatimage.identify_image( file_data)
                if fmt in [ 'heic']:
                    heif_file = pillow_heif.read_heif( org_path)
                    image = Image. frombytes( mode=heif_file.mode, size=heif_file.size, data=heif_file.data)
                    # 將要存儲的路徑及名稱
                    path, filename = os. path. split( org_path)
                    name, ext = os. path. splitext( filename)
                    file_path = os. path. join( dst_path, '%s.jpg' % name)
                    print( file_path)
                    # 保存圖片(JPEG格式)
                    image. save( file_path, "JPEG")
            except:
                print( 'except')
    else:
        print( org_path + 'is error format!')
    pass
# 主函數入口
def main():
    # dst path
    dst_path = r"D:\JPG"
    if os. path. exists( dst_path) is False:
        os. makedirs( dst_path)
        pass
    # org path
    org_path = r"D:\HEIC"
    # convert
    recyle_convert( org_path, dst_path)
    pass



if __name__ == '__main__':
    main()
登錄后免費查看全文
立即登錄
App下載
技術鄰APP
工程師必備
  • 項目客服
  • 培訓客服
  • 平臺客服

TOP

1
1
3