欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用python制作一個(gè)壓縮圖片小程序

 更新時(shí)間:2023年10月27日 16:30:11   作者:hbqjzx  
這篇文章主要為大家詳細(xì)介紹了如何使用python制作一個(gè)壓縮圖片小程序,文中的示例代碼簡(jiǎn)潔易懂,具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解下

學(xué)生正在學(xué)習(xí)圖像的編碼與壓縮,記錄一下這個(gè)python小程序,給他們提供一下幫助。需要用到PIL庫(kù),記得安裝:

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="打開(kāi)", 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='質(zhì)量(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="開(kāi)始?jí)嚎s", 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"壓縮過(guò)程中發(fā)生錯(cuò)誤:{e}")
 
if __name__ == '__main__':
    window = tk.Tk()
    app = ImageCompressor(window)
    window.mainloop()

知識(shí)補(bǔ)充

除了上文的方法,小編還為大家整理了其他python壓縮圖片的方法,希望對(duì)大家有所幫助

使用PIL庫(kù)壓縮圖片大小(按比例壓縮)

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實(shí)現(xiàn)批量壓縮圖片 無(wú)大小限制

# 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 -*-
"""腳本功能說(shuō)明:使用 tinypng api,一鍵批量壓縮指定文件(夾)所有文件"""
import os
import sys
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor # 線程池,進(jìn)程池
import json
import random
import requests
from you_get import common
from shutil import copyfile
def get_file_dir(file):
 """獲取文件目錄通用函數(shù)"""
 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'開(kāi)始下載文件 :%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("已存在,跳過(guò)壓縮")
  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("已跳過(guò)壓縮,并直接拷貝文件")
   try:
    copyfile(input_file, output_file)
   except IOError as e:
    print("Unable to copy file. %s" % e)
   return
  print("開(kāi)始?jí)嚎s")
  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'報(bào)錯(cuò)了:%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'目標(biāo)文件(夾)不存在,請(qǐng)確認(rèn)后重試。')
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'報(bào)錯(cuò)了:%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個(gè)線程執(zhí)行此任務(wù)
 download_thread_pool = ThreadPoolExecutor(10) # 定義5個(gè)線程執(zhí)行此任務(wù)
 process_pool = ProcessPoolExecutor(8) # 定義5個(gè)進(jìn)程
 len_param = len(sys.argv)
 if len_param != 2 and len_param != 3:
  print('請(qǐng)使用: %s [filepath]' % os.path.basename(sys.argv[0]))
 else:
  check_path(sys.argv[1])
  input("Press <enter> 請(qǐng)耐心等待\n")

到此這篇關(guān)于使用python制作一個(gè)壓縮圖片小程序的文章就介紹到這了,更多相關(guān)python壓縮圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中的TCP socket寫(xiě)法示例

    Python中的TCP socket寫(xiě)法示例

    最近在學(xué)習(xí)腳本語(yǔ)言python,所以下面這篇文章主要給大家介紹了關(guān)于Python中TCP socket寫(xiě)法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們一起來(lái)看看吧
    2018-05-05
  • Python入門學(xué)習(xí)之類的相關(guān)知識(shí)總結(jié)

    Python入門學(xué)習(xí)之類的相關(guān)知識(shí)總結(jié)

    今天帶大家復(fù)習(xí)python的基礎(chǔ)知識(shí),文中對(duì)類的相關(guān)知識(shí)作了非常詳細(xì)的介紹,對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • 淺談function(函數(shù))中的動(dòng)態(tài)參數(shù)

    淺談function(函數(shù))中的動(dòng)態(tài)參數(shù)

    下面小編就為大家?guī)?lái)一篇淺談function(函數(shù))中的動(dòng)態(tài)參數(shù)。小編覺(jué)得聽(tīng)不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-04-04
  • 淺談如何測(cè)試Python代碼

    淺談如何測(cè)試Python代碼

    今天帶大家了解如何用Python測(cè)試代碼,文中有非常詳細(xì)的介紹及代碼示例,對(duì)正在學(xué)習(xí)的小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • python 遞歸遍歷文件夾,并打印滿足條件的文件路徑實(shí)例

    python 遞歸遍歷文件夾,并打印滿足條件的文件路徑實(shí)例

    下面小編就為大家?guī)?lái)一篇python 遞歸遍歷文件夾,并打印滿足條件的文件路徑實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-08-08
  • 一文秒懂python讀寫(xiě)csv xml json文件各種騷操作

    一文秒懂python讀寫(xiě)csv xml json文件各種騷操作

    多年來(lái),數(shù)據(jù)存儲(chǔ)的可能格式顯著增加,但是,在日常使用中,還是以 CSV 、 JSON 和 XML 占主導(dǎo)地位。 在本文中,我將與你分享在Python中使用這三種流行數(shù)據(jù)格式及其之間相互轉(zhuǎn)換的最簡(jiǎn)單方法,需要的朋友可以參考下
    2019-07-07
  • python 正則表達(dá)式貪婪模式與非貪婪模式原理、用法實(shí)例分析

    python 正則表達(dá)式貪婪模式與非貪婪模式原理、用法實(shí)例分析

    這篇文章主要介紹了python 正則表達(dá)式貪婪模式與非貪婪模式原理、用法,結(jié)合實(shí)例形式詳細(xì)分析了python 正則表達(dá)式貪婪模式與非貪婪模式的功能、原理、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-10-10
  • python爬蟲(chóng)模塊URL管理器模塊用法解析

    python爬蟲(chóng)模塊URL管理器模塊用法解析

    這篇文章主要介紹了python爬蟲(chóng)模塊URL管理器模塊用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • NumPy數(shù)組復(fù)制與視圖詳解

    NumPy數(shù)組復(fù)制與視圖詳解

    NumPy 數(shù)組的復(fù)制和視圖是兩種不同的方式來(lái)創(chuàng)建新數(shù)組,它們之間存在著重要的區(qū)別,本文將給大家詳細(xì)介紹一下NumPy數(shù)組復(fù)制與視圖,并通過(guò)代碼示例講解的非常詳細(xì),需要的朋友可以參考下
    2024-05-05
  • 用Python進(jìn)行柵格數(shù)據(jù)的分區(qū)統(tǒng)計(jì)和批量提取

    用Python進(jìn)行柵格數(shù)據(jù)的分區(qū)統(tǒng)計(jì)和批量提取

    該教程其實(shí)源于web,我看到之后覺(jué)得很實(shí)用,于是自己又重復(fù)做了一遍,寫(xiě)了詳細(xì)的注釋分享給大家,希望對(duì)大家的研究有幫助,本文講述了柵格的分區(qū)統(tǒng)計(jì),批量提取,深化理解遍歷循環(huán)等內(nèi)容
    2021-05-05

最新評(píng)論