1. 程式人生 > 程式設計 >Python 實現判斷圖片格式並轉換,將轉換的影象存到生成的資料夾中

Python 實現判斷圖片格式並轉換,將轉換的影象存到生成的資料夾中

我就廢話不多說了,直接上程式碼吧!

import Image
from datetime import datetime
import os
str = '/home/dltest/caffe/examples/sgg_datas/images/result_test/zutest/' + datetime.now().strftime("%Y%m%d_%H%M%S")
 
while True==os.path.exists(str):
  str = str + datetime.now().strftime("%Y%m%d_%H%M%S")
  
os.makedirs(str)  #建立資料夾
 
imageFile = '/home/dltest/caffe/examples/sgg_datas/images/result_test/zutest/20form1.bmp' #圖片路徑
 
import imghdr
imgType = imghdr.what(imageFile) #獲取影象型別,返回bmp,jpg等
type1 = cmp(imgType,'bmp')  #判斷是否為bmp,jpg型別,若字元相等則返回值為 0 
type2 = cmp(imgType,'jpeg') 
type3 = cmp(imgType,'jpg') 
type = type1 *type2 *type3 #判斷是否為三種類型中的一類
if type != 0 : 
  #進行影象型別轉換,轉換為 jpg格式
  im = Image.open(imageFile) 
  str2 = str + '/' + '1.jpg'  #會自動替換原來的1.jpg
  im.save(str2) 
 
print('1')

以上這篇Python 實現判斷圖片格式並轉換,將轉換的影象存到生成的資料夾中就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。