使用python制作一个压缩图片小程序

 更新时间:2023年10月27日 16:30:11   作者:hbqjzx  
这篇文章主要为大家详细介绍了如何使用python制作一个压缩图片小程序,文中的示例代码简洁易懂,具有一定的学习价值,感兴趣的小伙伴可以了解下

学生正在学习图像的编码与压缩,记录一下这个python小程序,给他们提供一下帮助。需要用到PIL库,记得安装:

pip install pillow

完整代码

import tkinter as tk
from tkinter import filedialog 
from PIL import Image
import tkinter.messagebox as messagebox
 
class ImageCompressor:
    def __init__(self, window):
        self.window = window
        self.window.title("图片压缩工具By ZYX 2023")
 
        self.source_path = tk.StringVar()
        self.output_path = tk.StringVar()
 
        frame1 = tk.Frame(window)
        frame1.pack(padx=5, pady=5)
 
        lbl_source = tk.Label(frame1, text="原始图片路径:")
        lbl_source.pack(side=tk.LEFT)
 
        entry_source = tk.Entry(frame1,textvariable=self.source_path, width=40)
        entry_source.pack(side=tk.LEFT)
 
        btn_source =tk.Button(frame1, text="打开", command=self.open_source_image)
        btn_source.pack(side=tk.LEFT)
 
        frame2 = tk.Frame(window)
        frame2.pack(padx=5, pady=5)
 
        lbl_output = tk.Label(frame2, text="输出图片路径:")
        lbl_output.pack(side=tk.LEFT)
 
        entry_output = tk.Entry(frame2,textvariable=self.output_path, width=40)
        entry_output.pack(side=tk.LEFT)
 
        btn_output =tk.Button(frame2, text="保存", command=self.save_output_image)
        btn_output.pack(side=tk.LEFT)
 
        quality_label = tk.Label(window, text='质量(1-95):')
        quality_label.pack(pady=5)
 
        self.quality_slider = tk.Scale(window, from_=1, to=95,
            length=400,tickinterval=19,
            orient='horizontal', resolution=1)
        self.quality_slider.set(80)
        self.quality_slider.pack()
 
        btn_compress =tk.Button(window, text="开始压缩", command=self.compress_image)
        btn_compress.pack(pady=10)
 
    def open_source_image(self):
        file_path = filedialog.askopenfilename()
        self.source_path.set(file_path)
 
    def save_output_image(self):
        file_path = filedialog.asksaveasfilename(defaultextension=".jpg")
        self.output_path.set(file_path)
 
    def compress_image(self):
        try:
            img = Image.open(self.source_path.get())
            img.save(self.output_path.get(), "JPEG", quality=self.quality_slider.get())
            messagebox.showinfo("成功", "图片压缩成功!")
        except Exception as e:
            messagebox.showerror("失败", f"压缩过程中发生错误:{e}")
 
if __name__ == '__main__':
    window = tk.Tk()
    app = ImageCompressor(window)
    window.mainloop()

知识补充

除了上文的方法,小编还为大家整理了其他python压缩图片的方法,希望对大家有所帮助

使用PIL库压缩图片大小(按比例压缩)

from PIL import Image

infile = 'cxq1.jpg'
outfile = 'cxq2.jpg'
im = Image.open(infile)
(x,y) = im.size #read image size
x_s = 1000 #define standard width
y_s = int(y * x_s / x) #calc height based on standard width
out = im.resize((x_s,y_s)) #resize image with high-quality
out.save(outfile)

print('original size: ',x,y)
print('adjust size: ',x_s,y_s)

Python实现批量压缩图片 无大小限制

# coding=utf-8
# @Time : 2020/6/20 9:39 
# @Author : mxz
# @File : image_zip.py 
# @Software: PyCharm

import tinify
import os

tinify.key = ''
path = r""

for root, dirs, files in os.walk(path):
    for file in files:
        imgpath = os.path.join(root, file)
        print("compressing ..."+ imgpath)
        tinify.from_file(imgpath).to_file(imgpath)

python批量压缩照片

# -*- coding: utf-8 -*-
"""脚本功能说明:使用 tinypng api,一键批量压缩指定文件(夹)所有文件"""
import os
import sys
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor # 线程池,进程池
import json
import random
import requests
from you_get import common
from shutil import copyfile
def get_file_dir(file):
 """获取文件目录通用函数"""
 fullpath = os.path.abspath(os.path.realpath(file))
 return os.path.dirname(fullpath)
def check_suffix(file_path):
 """检查指定文件的后缀是否符合要求"""
 file_path_lower = file_path.lower()
 return (file_path_lower.endswith('.png')
   or file_path_lower.endswith('.jpg')
   or file_path_lower.endswith('.jpeg'))
def download_tinypng(input_file, url, output_file):
 file_name = os.path.basename(input_file)
 arr = file_name.split('.')
 new_file_name = arr[len(arr) - 2] + '_compress'
 new_output_file = os.path.join(os.path.dirname(output_file), arr[len(arr) - 2] + '_compress.' + arr[len(arr) - 1])
 print(u'开始下载文件 :%s' % new_output_file)
 # print(os.path.splitext(os.path.basename(output_file))[0])
 sys.argv = ['you-get', '-o', os.path.dirname(
  output_file), '-O', new_file_name, url]
 common.main()
 old_size = os.path.getsize(input_file)
 new_size = os.path.getsize(new_output_file)
 print(u'文件保存地址:%s' % new_output_file)
 print(u'压缩后文件大小:%d KB' % (new_size / 1024))
 print(u'压缩比: %d%%' % ((old_size - new_size) * 100 / old_size))
def compress_by_tinypng(input_file):
 if not check_suffix(input_file):
  print(u'只支持png\\jpg\\jepg格式文件:' + input_file)
  return
 file_name = os.path.basename(input_file)
 arr = file_name.split('.')
 new_file_name = arr[len(arr) - 2] + '_compress.' + arr[len(arr) - 1]
 output_path = os.path.join(get_file_dir(input_file), 'compress_output')
 output_file = os.path.join(output_path, new_file_name)
 if not os.path.isdir(output_path):
  os.makedirs(output_path)
 if (os.path.exists(output_file)):
  print("已存在,跳过压缩")
  return
 try:
  old_size = os.path.getsize(input_file)
  print(u'压缩前文件名:%s文件大小:%d KB' % (input_file, old_size / 1024))
  if (old_size < 1024 * 1024):
   print("已跳过压缩,并直接拷贝文件")
   try:
    copyfile(input_file, output_file)
   except IOError as e:
    print("Unable to copy file. %s" % e)
   return
  print("开始压缩")
  shrink_image(input_file)
  print(u'文件压缩成功:%s' % input_file)
  # download_thread_pool.submit(download_tinypng, source, input_file, output_file)
 except Exception as e:
  print(u'报错了:%s' % e)
def check_path(input_path):
 """如果输入的是文件则直接压缩,如果是文件夹则先遍历"""
 if os.path.isfile(input_path):
  compress_by_tinypng(input_path)
 elif os.path.isdir(input_path):
  dirlist = os.walk(input_path)
  for root, dirs, files in dirlist:
   if (not (root.endswith("\\compress_output") or root.endswith("/compress_output"))):
    i = 0
    for filename in files:
     i = i + 1
     process_pool.submit(compress_by_tinypng, os.path.join(
      root, filename))
     # compress_by_tinypng(os.path.join(root, filename))
 else:
  print(u'目标文件(夹)不存在,请确认后重试。')
def list_images(path):
 images = None
 try:
  if path:
   os.chdir(path)
  full_path = os.getcwd()
  files = os.listdir(full_path)
  images = []
  for file in files:
   ext = os.path.splitext(file)[1].lower()
   if ext in ('.jpg', '.jpeg', '.png'):
    images.append(os.path.join(full_path, file))
 except:
  pass
 return images
def shrink_image(file_path):
 print(u'源文件地址:%s' % file_path)
 result = shrink(file_path)
 if result:
  output_path = generate_output_path(file_path)
  url = result['output']['url']
  print(u'下载地址:%s' % url)
  download_tinypng(file_path, url, output_path)
  # download_thread_pool.submit(download_tinypng, file_path, url, output_path)
  # response = requests.get(url)
  # with open(output_path, 'wb') as file:
  #  file.write(response.content)
  # print(u'文件保存地址:%s' % output_path)
  # print('%s %d=>%d(%f)' % (
  #  result['input']['type'],
  #  result['input']['size'],
  #  result['output']['size'],
  #  result['output']['ratio']
  #  ))
 else:
  print('压缩失败')
def shrink(file_path):
 url = 'https://tinypng.com/web/shrink'
 headers = {
  'Cache-Control': 'no-cache',
  'Content-Type': 'application/x-www-form-urlencoded',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44',
  'X-Forwarded-For': get_random_ip()
 }
 result = None
 try:
  file = open(file_path, 'rb')
  response = requests.post(url, headers=headers, data=file)
  result = json.loads(response.text)
 except Exception as e:
  print(u'报错了:%s' % e)
  if file:
   file.close()
 if result and result['input'] and result['output']:
  return result
 else:
  return None
def generate_output_path(file_path):
 parent_path = os.path.abspath(os.path.dirname(file_path))
 output_path = os.path.join(parent_path, 'compress_output')
 if not os.path.isdir(output_path):
  os.mkdir(output_path)
 return os.path.join(output_path, os.path.basename(file_path))
def get_random_ip():
 ip = []
 for i in range(4):
  ip.append(str(random.randint(0 if i in (2, 3) else 1, 254)))
 return '.'.join(ip)
if __name__ == '__main__':
 thread_pool = ThreadPoolExecutor(5) # 定义5个线程执行此任务
 download_thread_pool = ThreadPoolExecutor(10) # 定义5个线程执行此任务
 process_pool = ProcessPoolExecutor(8) # 定义5个进程
 len_param = len(sys.argv)
 if len_param != 2 and len_param != 3:
  print('请使用: %s [filepath]' % os.path.basename(sys.argv[0]))
 else:
  check_path(sys.argv[1])
  input("Press <enter> 请耐心等待\n")

到此这篇关于使用python制作一个压缩图片小程序的文章就介绍到这了,更多相关python压缩图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中的TCP socket写法示例

    Python中的TCP socket写法示例

    最近在学习脚本语言python,所以下面这篇文章主要给大家介绍了关于Python中TCP socket写法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或工作具有一定的参考学习价值,需要的朋友们一起来看看吧
    2018-05-05
  • Python入门学习之类的相关知识总结

    Python入门学习之类的相关知识总结

    今天带大家复习python的基础知识,文中对类的相关知识作了非常详细的介绍,对正在学习python的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05
  • 浅谈function(函数)中的动态参数

    浅谈function(函数)中的动态参数

    下面小编就为大家带来一篇浅谈function(函数)中的动态参数。小编觉得听不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • 浅谈如何测试Python代码

    浅谈如何测试Python代码

    今天带大家了解如何用Python测试代码,文中有非常详细的介绍及代码示例,对正在学习的小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • python 递归遍历文件夹,并打印满足条件的文件路径实例

    python 递归遍历文件夹,并打印满足条件的文件路径实例

    下面小编就为大家带来一篇python 递归遍历文件夹,并打印满足条件的文件路径实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • 一文秒懂python读写csv xml json文件各种骚操作

    一文秒懂python读写csv xml json文件各种骚操作

    多年来,数据存储的可能格式显著增加,但是,在日常使用中,还是以 CSV 、 JSON 和 XML 占主导地位。 在本文中,我将与你分享在Python中使用这三种流行数据格式及其之间相互转换的最简单方法,需要的朋友可以参考下
    2019-07-07
  • python 正则表达式贪婪模式与非贪婪模式原理、用法实例分析

    python 正则表达式贪婪模式与非贪婪模式原理、用法实例分析

    这篇文章主要介绍了python 正则表达式贪婪模式与非贪婪模式原理、用法,结合实例形式详细分析了python 正则表达式贪婪模式与非贪婪模式的功能、原理、用法及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • python爬虫模块URL管理器模块用法解析

    python爬虫模块URL管理器模块用法解析

    这篇文章主要介绍了python爬虫模块URL管理器模块用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • NumPy数组复制与视图详解

    NumPy数组复制与视图详解

    NumPy 数组的复制和视图是两种不同的方式来创建新数组,它们之间存在着重要的区别,本文将给大家详细介绍一下NumPy数组复制与视图,并通过代码示例讲解的非常详细,需要的朋友可以参考下
    2024-05-05
  • 用Python进行栅格数据的分区统计和批量提取

    用Python进行栅格数据的分区统计和批量提取

    该教程其实源于web,我看到之后觉得很实用,于是自己又重复做了一遍,写了详细的注释分享给大家,希望对大家的研究有帮助,本文讲述了栅格的分区统计,批量提取,深化理解遍历循环等内容
    2021-05-05

最新评论