99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁大數據時代教你用 Python 快速批量轉換 HEIC 文件
教你用 Python 快速批量轉換 HEIC 文件
2021-12-23
收藏

作者:星安果

來源:AirPython

1. 前言

大家好,我是安果!

最近打算做一批日歷給親朋好友,但是從 iPhone上導出的照片格式是 HEIC 格式,而商家的在線制作網站不支持這種圖片格式

PS:HEIC 是蘋果采用的新的默認圖片格式,它能在不損失圖片畫質的情況下,減少圖片大小

有很多在線網站支持圖片批量轉換,但是安全隱私又沒法得到保證;如果使用 PS 等軟件去一張張轉換,浪費時間的同時效率太低

本篇文章將使用 Python 批量實現 HEIC 圖片文件的格式轉換

2. 準備

首先,我們安裝 pyheif 依賴包

Linux 和 Mac OS 可以通過下面鏈接選擇合適的方式進行安裝

https://pypi.org/project/pyheif/

如果是 Windows,我們只能下載 whl 依賴文件,使用 pip 命令進行安裝

注意:我們需要根據系統(tǒng)及Python 版本選擇對應的文件進行安裝

# 比如,本機是win10+64位 + Python3.7
# 通過下面鏈接下載文件:pyheif?0.6.1?cp37?cp37m?win_amd64.whl
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyheif
# 然后進行虛擬環(huán)境
# 使用pip3命令安裝whl文件
pip3 install pyheif?0.6.1?cp37?cp37m?win_amd64.whl

然后,安裝 PIL 依賴,用于圖片處理

# 安裝依賴
pip3 install Pillow

3. 實戰(zhàn)

首先,遍歷源文件夾及子文件夾,獲取所有 HEIC 格式(不區(qū)分大小寫)的圖片

import pathlib
import os
def get_all_heic_imgs():
"""
獲取所有heic格式的圖片
:return:
"""
# heif_image_paths = glob.glob(r"{}/*.heic".format(source_path))
# 滿足條件的文件列表
filelist = []
for root, dirnames, filenames in os.walk(source_path):
for filename in filenames:
# filename:文件名、root:文件對應的目錄
# 獲取文件后綴名
file_end = pathlib.Path(filename).suffix
# 文件名(不帶后綴)
file_name = pathlib.Path(filename).name.split(".")[-2]
if file_end in ['.heic', '.HEIC']:
# 文件的完整目錄
# file_path = os.path.join(root, filename)
filelist.append({
"filename": file_name,
"filepath": os.path.join(root, filename)
})
return filelist

然后,遍歷文件列表,使用 pyheif 讀取文件,使用PIL 轉為二進制圖片,以JPG 格式保存到目標文件夾下

import pyheif
from PIL import Image
# 讀取文件
img = pyheif.read(filepath)
img_bytes = Image.frombytes(mode=img.mode, size=img.size, data=img.data)

# 文件保存完整目錄
target_file_path = '{}/{}_{}.jpg'.format(target_path, filename, generate_random_num(6))
# 保存
img_bytes.save(target_file_path, format="jpeg")

由于圖片數目很多,圖片讀取、圖片保存都是耗時的 IO 操作,最后對程序進行改造,利用多線程加快圖片轉換

另外,圖片可能會存在文件名重名,最后保存的文件名追加了一個隨機的字符串

import threading
def generate_random_num(count):
"""
產生一段隨機的字符串
:param count:
:return:
"""
return ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', count))
def convert_heic_to_jpg(file, semaphore):
"""
heic格式轉jpg
:param files:
:return:
"""
semaphore.acquire()
...
#文件操作
# 釋放
semaphore.release()
if __name__ == '__main__':
...
# 定義信號量,并發(fā)處理文件IO
semaphore = threading.BoundedSemaphore(20)
for file in files:
t = threading.Thread(target=convert_heic_to_jpg, args=(file, semaphore))
t.start()

4. 最后

通過上面的操作就可以快速將 HEIC 文件批量轉換為 JPG 文件,當然如果想轉為其他圖片,比如:PNG,只需要更改 PIL 保存圖片的格式即可

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數1:配置參數 // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產品形式,包括:float,popup width: "280px", https: true // 更多配置參數說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }