python图片转换案例(内含多种场景的案例)
程序员文章站
2022-06-02 16:23:39
废话不多说!上来就是精华案例一:业务场景:一个文件夹中有很多图片,图片的格式有两种一个是TIF,一个是GIF,两两对应,如果有单独的存在,那么就需要把对应的给图片转换出来例如:只有1.GIF 那么我就需要将1.TIF 给弄出来或者 只有2.TIF那就就需要将2.GIF给弄出来方法一import osfrom PIL import Imagepath = "C:\\Users\\Administrator\\Desktop\\tif" #文件夹目录dirs= os.listdir(p...
废话不多说!上来就是精华
案例一:
业务场景:
一个文件夹中有很多图片,图片的格式有两种一个是TIF,一个是GIF,两两对应,如果有单独的存在,那么就需要把对应的给图片转换出来
例如:只有1.GIF 那么我就需要将1.TIF 给弄出来或者 只有2.TIF那就就需要将2.GIF给弄出来
方法一
import os
from PIL import Image
path = "C:\\Users\\Administrator\\Desktop\\tif" #文件夹目录
dirs= os.listdir(path) #得到文件夹下的所有文件名称
list2=[]
list1=[]
for file in dirs:
if file.endswith(".tif"):
list1.append(file.split(".")[0])
if file.endswith(".gif"):
list2.append(file.split(".")[0])
imagesList=[]
d=[i for i in list1 if i not in list2]
for only_image in d:
for images in dirs:
if images.__contains__(only_image):
imagesList.append(images)
f=[i for i in list2 if i not in list1]
for only_image in f:
for images in dirs:
if images.__contains__(only_image):
imagesList.append(images)
print(imagesList)
def IsValidImage(img_path):
"""
判断文件是否为有效(完整)的图片
:param img_path:图片路径
:return:True:有效 False:无效
"""
bValid = True
try:
Image.open(img_path).verify()
except:
bValid = True
return bValid
def transimgTIF(img_path):
"""
转换图片格式
:param img_path:图片路径
:return: True:成功 False:失败
"""
if IsValidImage(img_path):
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".tif"
print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
def transimgGIF(img_path):
"""
转换图片格式
:param img_path:图片路径
:return: True:成功 False:失败
"""
if IsValidImage(img_path):
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".gif"
print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
if __name__ == '__main__':
for ImagePath in imagesList:
if ImagePath.__contains__(".tif"):
# print(path+'\\'+ImagePath)
a=transimgGIF(path+'\\'+ImagePath)
print(a)
if ImagePath.__contains__(".gif"):
# print(path+'\\'+ImagePath)
a=transimgTIF(path+'\\'+ImagePath)
print(a)
方法二
import os,datetime
from PIL import Image
path = 'C:\\Users\\Administrator\\Desktop\\image'
start = datetime.datetime.now()
def IsValidImage(img_path):
bValid = True
try:
Image.open(img_path).verify()
except:
bValid = False
return bValid
def transimgTIF(img_path):
if IsValidImage(img_path):
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".tif"
# print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
def transimgGIF(img_path):
if IsValidImage(img_path):
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".gif"
# print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
def fun(path):#含子文件夹
for (root, dirs, files) in os.walk(path):
for filename in files:
ImagePath=os.path.join(root,filename)
if os.path.exists(ImagePath.split(".")[0]+'.tif')& os.path.exists(ImagePath.split(".")[0]+'.gif'):
print()
else:
if ImagePath.__contains__(".gif"):
transimgTIF(ImagePath)
if ImagePath.__contains__(".tif"):
transimgGIF(ImagePath)
fun(path)
end = datetime.datetime.now()
print(end-start)
方法三
import os,datetime
from PIL import Image
path = 'C:\\Users\\Administrator\\Desktop\\tgif'
start = datetime.datetime.now()
def IsValidImage(img_path):
bValid = True
try:
Image.open(img_path).verify()
except:
bValid = False
return bValid
#594,398
def transimgTIF(img_path):
if IsValidImage(img_path):
# print(img_path+"传递过来的是gif")
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".tif"
print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
def transimgGIF(img_path):
if IsValidImage(img_path):
# print(img_path+"传递过来的是tif")
try:
str = img_path.rsplit(".", 1)
output_img_path = str[0] + ".gif"
print(output_img_path)
im = Image.open(img_path)
im.save(output_img_path)
return True
except:
return False
else:
return False
def fun(path):#含子文件夹
imagePath=[]
for (root, dirs, files) in os.walk(path):
for filename in files:
ImagePath=os.path.join(root,filename)
imagePath.append(ImagePath)
conn=imagePath
set_dir=set([ i.rsplit(".")[0] for i in conn])
# print(set_dir)
for dir in set_dir:
if dir+".tif" not in imagePath:
# print(dir+".gif")
transimgTIF(dir+".gif")
if dir + ".gif" not in imagePath:
# print(dir + ".tif")
transimgGIF(dir + ".tif")
fun(path)
end = datetime.datetime.now()
print(end-start)
案例二:
业务场景:
方法一
import os,datetime
import shutil
from PIL import Image
'''
@path: 所有图片字母里的父目录 例如:
C:\\Users\\Administrator\\Desktop\\udev\\adcc\\dsdsds\\ccss\\group\\DDMS
C:\\Users\\Administrator\\Desktop\\udev\\adcc\\dsdsds\\ccss\\group\\DDMA
C:\\Users\\Administrator\\Desktop\\udev\\adcc\\dsdsds\\ccss\\group\\DDME
@Parent_directory:为所有子文件的父文件夹的名称 父文件夹名称就为:group
@new_path:要存放的新路径
'''
path = 'C:\\Users\\Administrator\\Desktop\\udev\\adcc\\dsdsds\\ccss\\group'
Parent_directory='group'
new_path='C:\\Users\Administrator\Desktop\ImageTIF'
def fun(path):#含子文件夹
for (root, dirs, files) in os.walk(path):
for filename in files:
'''
ImagePath为所有图片的路径
'''
ImagePath=os.path.join(root,filename)
'''
判断A.tif和A.gif是否都存在
'''
if os.path.exists(ImagePath.split(".")[0]+'.tif')& os.path.exists(ImagePath.split(".")[0]+'.gif'):
continue
else:
'''
将对应不上的.tif取出来
'''
if ImagePath.__contains__('.tif'):
'''
str为
ImagePath='C:\\Users\\Administrator\\Desktop\\udev\\caca\\3310A11.tif'
str=[C:\\Users\\Administrator\\Desktop\\udev\\caca\\3310A11,.tif]
str[0]=C:\\Users\\Administrator\\Desktop\\udev\\caca\\3310A11
new_ImagePath=每个子目录的文件名称
'''
str = ImagePath.rsplit(".", 1)
new_ImagePath = str[0][str[0].index(Parent_directory) + len(Parent_directory + "\\"):-1].split('\\')[0]
'''
判断
new_path='C:\\Users\Administrator\Desktop\ImageTIF'
new_ImagePath=‘DDMAK01’
new_path+new_ImagePath是否存在
存在直接将 ImagePath='C:\\Users\\Administrator\\Desktop\\udev\\caca\\3310A11.tif' 复制到 new_path+new_ImagePath
不存在先创建 再进行复制
'''
if os.path.exists(new_path+"\\"+new_ImagePath):
shutil.copy(ImagePath,new_path+"\\"+new_ImagePath)
else:
os.mkdir(new_path + '\\' + new_ImagePath)
shutil.copy(ImagePath, new_path + "\\" + new_ImagePath)
fun(path)
很多层目录的图片该怎么办
import os
from PIL import Image
#原图片路径
path = 'C:\\Users\\Administrator\\Desktop\\group'
Parent_directory="group"
#GIF图片存放路径
new_Path='C:\\Users\\Administrator\\Desktop\\ce'
def IsValidImage(img_path):
bValid = True
try:
Image.open(img_path).verify()
except:
bValid = False
return bValid
def transimgGIF(img_path):
if IsValidImage(img_path):
try:
str = img_path.rsplit(".", 1)
new_ImagePath=str[0][str[0].index(Parent_directory) + len(Parent_directory+"\\"):-1]
output_img_path = new_Path+'\\'+new_ImagePath+ ".jpg"
im = Image.open(img_path)
im.save(output_img_path,quality=100)
return True
except:
return False
else:
return False
def fun(path):
for (root, dirs, files) in os.walk(path):
for filename in files:
ImagePath=os.path.join(root,filename)
if ImagePath.__contains__('.tif'):
new_ImagePath = root[root.index(Parent_directory) + len(Parent_directory + "\\"):]
print(new_Path + '\\' + new_ImagePath)
if os.path.exists(new_Path + '\\' + new_ImagePath):
transimgGIF(ImagePath)
else:
os.makedirs(new_Path+'\\'+new_ImagePath)
transimgGIF(ImagePath)
if __name__ == '__main__':
if os.path.exists(new_Path):
fun(path)
else:
os.makedirs(new_Path)
fun(path)
本文地址:https://blog.csdn.net/weixin_43563705/article/details/107068864
上一篇: 写给新手站长:Linux主机挑选秘诀
下一篇: 关于响应式设计的现状与趋势的详细分析