In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This issue of the content of the editor will bring you about the python batch compression image of the complete steps is, the article is rich in content and professional perspective for everyone to analyze and describe, after reading this article, I hope you can get something.
Background
Today, at work, my colleagues encountered a problem of uploading pictures: the image size required by the system cannot exceed 512KB. But my colleagues have a lot of pictures. It would be crushing if every photo was compressed in ps. So I wrote a script that could compress pictures in batches to a specified size. Directly benefit colleagues and improve their work efficiency.
Solution
In fact, there is no need to sell, that is, you can use python's pillow package to compress the picture, if a picture has been compressed to the specified size, then stop compression, if the specified size is not reached, then compress the compressed picture again until it is compressed to a custom range.
But why not find the code on the Internet? I looked for it, too, but found that a lot of the code quality was uneven, it didn't achieve the effect I wanted, and it was not elegant. So I casually wrote a code, not only the code is simple, but also the logic is clear, and finally for efficiency, I also do a parallel, using 10 processes at the same time. To tell you the truth, it was really fast.
Operation procedure requirements
The default is the environment that uses Anaconda.
Put all the images you want to compress in a folder, and then each image can only be in the following three formats: png,jpg, jpeg. Not even if it's PNG. Because PNG is an uppercase for png.
The compressed size of the image set in the code is 512KB, so you can set the target_size in the code to 500, as long as it is smaller than 512KB.
Then download my code from GitHub. The code link is: https://github.com/yuanzhoulvpi2017/tiny_python/blob/main/image_compression/ic.py
Steps
Here I put all the pictures in a folder, the name of the folder is history screenshot. Then my screenshot of the history and the ic.py code are placed in the little_code folder.
Under the little_code folder, open the terminal.
Scripts that run directly:
Python ic.py xxx_ folder
Wait a while, and all the pictures in the entire folder will be converted.
Complete code:
If I can't go to GitHub, I'll just put the code here and save it as a python file. For example, the saved file is called ic.py
From PIL import Imagefrom globimport globimport osfrom tqdmimport tqdmimport shutilimport sysfrom itertools import chainfrom multiprocessing import Pool# image_dir = "image_dir" template_dir = 'template'output_dir =' output'error_dir = 'error'def clean_dir (dir_name): if os.path.exists (dir_name): shutil.rmtree (dir_name) os.makedirs (dir_name) else: os.makedirs (dir_name) # image_file_list = glob (f "{image_dir} / *") # image_file_listdef imagesize (filepath): "" get the disk size of the file: param filepath:: return: "return os.path.getsize (filepath) / 1024def compress_image (image_path): raw_image = Image.open (image_path) temp_image_name = image_path.split (os.sep) [- 1] template_image = os.path.join (template_dir) Temp_image_name) output_image = os.path.join (output_dir, temp_image_name) error_image = os.path.join (error_dir, temp_image_name) target_size = 500 # kb try: if imagesize (image_path)
< target_size: shutil.copyfile(image_path, output_image) else: width, height = raw_image.size raw_image.resize((int(width * 0.9), int(height * 0.9)), Image.ANTIALIAS).save(template_image) while imagesize(template_image) >Target_size: template_iamge2 = Image.open (template_image) width_2, height_2 = template_iamge2.size template_iamge2.resize (int (width_2 * 0.9), int (height_2 * 0.9), Image.ANTIALIAS) .save (template_image) shutil.copyfile (template_image, output_image) except Exception as e: shutil.copyfile (image_path Error_image) print (f 'file save failed: {image_path}') # print (e) if _ _ name__ = ='_ _ main__': # batch create folder [clean_dir (I) for i in [template_dir, output_dir, error_dir]] image_dir = sys.argv [1] image_file_list = list (* [glob (os.path.join (image_dir) I) for i in ['* .png','* .jpg','* .jpeg'])) # for temp_image_path in tqdm (image_file_list): # compress_image (temp_image_path) print (f'\ n\ nFile Save parent directory: {os.getcwd ()}\ n'f 'output file location: {os.path.join (os.getcwd ()) Output_dir)}\ n\ n') # parallel P = Pool (processes=10) pbar = tqdm (total=len (image_file_list)) res_temp = [P.apply_async (func=compress_image, args= (I,)) Callback=lambda _: pbar.update (1) for i in image_file_list] _ = [res.get () for res in res_temp] attached: set the size of the picture to the specified size in batch import osfrom PIL import Image # Source directory project_dir = os.path.dirname (os.path.abspath (_ _ file__)) input = os.path.join (project_dir, 'src') # output directory output = os.path.join (project_dir 'dest') def modify (): # switching directory os.chdir (input) # traversing all files under the directory for image_name in os.listdir (os.getcwd ()): print (image_name) im = Image.open (os.path.join (input, image_name)) im.thumbnail ((128,128)) im.save (os.path.join (output) Image_name)) if _ _ name__ = ='_ _ main__': modify () these are the complete steps of the python batch compression image shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.