SoFunction
Updated on 2024-11-15

python realize batch modify image format and size

This article example for you to share the python batch processing image specific code for your reference, the specific content is as follows

A company project requires all 4096x4096 pictures are converted into 2048x2048 pictures, this batch conversion of picture size software online a lot of my coworkers originally used the United States to see the batch conversion, but a little bit of trouble, each time you also need to specify the picture to be converted to the input path and the output path, and each time can only deal with a folder, it's very cumbersome! So I thought of the almighty Python, and then wrote a script to batch processing of pictures, the same root directory of all the folders of the sub-files, etc., all the pictures will be processed.

The code also adds a lot of exception catching mechanisms and hints, which I hope will be helpful.

Remarks:

1. Imported the PIL library, is used to deal with pictures, very powerful;

2. imported win32 library, is to determine the hidden files with our project needs to delete the hidden files, do not need to directly find the deletion.

3. import send2trash library, is the deleted files into the trash, rather than permanently deleted, this I just prevent the deletion of useful files and get, a little strict right, do not need to be deleted ah.

4. I this script is Python2.7 written, but in dealing with the Chinese encoding is very disgusting, although I finally solved the solution, this solution, I will then write a separate article, but at the moment I am recommending that we do not use the version of python. I've been told that the encoding problem has been solved in some versions of python. I hope you'll take my advice.

#coding=utf-8 
import sys 
import os, glob 
import platform 
import win32file,win32con 
from PIL import Image 
from send2trash import send2trash 
 
reload(sys) 
('utf-8') 
 
#new_width =2048 
#width =int(raw_input("the width U want:")) 
#imgslist = (path+'/*.*') 
 
ShuiPing="Level" 
ShiZhuang="Sagittal." 
GuanZhuang="Crowned." 
 
def Py_Log(_string): 
  print "----"+_string.decode('utf-8')+"----" 
 
def is_windows_system(): 
  return 'Windows' in () 
 
def is_hiden_file(file_Path):  
  if is_windows_system():  
    fileAttr = (file_Path) 
    if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :  
      return True  
    return False  
  return False 
 
def remove_hidden_file(file_path): 
  send2trash(file_path) 
  print "Delete hidden file path:"+file_path 
 
def astrcmp(str1,str2): 
  return ()==() 
 
def resize_image(img_path): 
  try: 
    mPath, ext = (img_path) 
    if (astrcmp(ext,".png") or astrcmp(ext,".jpg")): 
      img = (img_path) 
      (width,height) =  
       
      if(width != new_width): 
        new_height = int(height * new_width / width) 
        out = ((new_width,new_height),) 
        new_file_name = '%s%s' %(mPath,ext) 
        (new_file_name,quality=100) 
        Py_Log("The image size was changed to:"+str(new_width)) 
      else: 
        Py_Log("Image is correctly sized and unaltered") 
    else: 
      Py_Log("Not in picture format") 
  except Exception,e: 
    print e 
 
#Change image type
def change_img_type(img_path): 
  try: 
    img = (img_path) 
    ('new_type.png') 
  except Exception,e: 
    print e 
 
# Handle remote images
def handle_remote_img(img_url): 
  try: 
    request = (img_url) 
    img_data = (request).read() 
    img_buffer = (img_data) 
    img = (img_buffer) 
    ('') 
    (width,height) =  
    out = ((200,height * 200 / width),) 
    ('remote_small.jpg') 
  except Exception,e: 
    print e 
 
def rename_forder(forder_path): 
  Py_Log("------------rename_forder--------------------------") 
  names = (forder_path) 
  try: 
    if(unicode(ShuiPing) in unicode(names[1],'gbk')): 
      (forder_path,names[0]+"\\"+"01") 
      Py_Log(names[1]+"-->"+"01") 
    if(unicode(ShiZhuang) in unicode(names[1],'gbk')): 
      (forder_path,names[0]+"\\"+"02") 
      Py_Log(names[1]+"-->"+"02") 
    if(unicode(GuanZhuang) in unicode(names[1],'gbk')): 
      (forder_path,names[0]+"\\"+"03") 
      Py_Log(names[1]+"-->"+"03") 
  except Exception,e: 
    print e 
 
def BFS_Dir(dirPath, dirCallback = None, fileCallback = None): 
  queue = [] 
  ret = [] 
  (dirPath); 
  while len(queue) > 0: 
    tmp = (0) 
    if((tmp)): 
      (tmp) 
      for item in (tmp): 
        ((tmp, item)) 
      if dirCallback: 
        dirCallback(tmp) 
    elif((tmp)): 
      (tmp) 
      if fileCallback: 
        fileCallback(tmp) 
  return ret 
 
def DFS_Dir(dirPath, dirCallback = None, fileCallback = None): 
  stack = [] 
  ret = [] 
  (dirPath); 
  while len(stack) > 0: 
    tmp = (len(stack) - 1) 
    if((tmp)): 
      (tmp) 
      for item in (tmp): 
        ((tmp, item)) 
      if dirCallback: 
        dirCallback(tmp) 
    elif((tmp)): 
      (tmp) 
      if fileCallback: 
        fileCallback(tmp) 
  return ret 
 
def printDir(dirPath): 
  print "dir: " + dirPath 
  if(is_hiden_file(dirPath)): 
    remove_hidden_file(dirPath) 
  else: 
    rename_forder(dirPath) 
 
def printFile(dirPath): 
  print "file: " + dirPath 
  resize_image(dirPath) 
  return True 
 
 
if __name__ == '__main__': 
  while True: 
    path = raw_input("Path:") 
    new_width =int(raw_input("the width U want:")) 
    try: 
      b = BFS_Dir(path , printDir, printFile) 
      Py_Log ("\r\n   **********\r\n"+"********* Image Processing Complete *********"+"\r\n  **********\r\n") 
    except: 
      print "Unexpected error:", sys.exc_info() 
    raw_input('press enter key to rehandle') 

This is the whole content of this article.