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

python如何實現圖片壓縮

 更新時間:2020年09月11日 09:49:31   作者:大飛  
這篇文章主要介紹了python如何實現圖片壓縮,幫助大家更好的利用python處理圖片,感興趣的朋友可以了解下

本工具是通過將圖片上傳到第三方網站tinypng,進行壓縮后下載,覆蓋本地圖片,tinypng是一個強大的圖片處理網站,目前最可靠的無損壓縮網站。

代碼如下:

import requests
from idna import unicode
from selenium import webdriver
import time
import os

browser = webdriver.Firefox(executable_path='/Users/lyf/Library/Google/geckodriver')



def tiny_png(url):
  # browser.get('https://tinypng.com/')
  upload_file = browser.find_element_by_tag_name("input")
  try:
    upload_file.send_keys(url)
    browser.implicitly_wait(20)
    a = browser.find_element_by_link_text('download')
    img_url = a.get_attribute('href')
    print(img_url)
    r = requests.get(img_url)
    with open(url, 'wb') as f:
      f.write(r.content)
    browser.refresh()
    time.sleep(2)
  except Exception as e:
    print(e)


def is_need_compress(img_path):
  """
  判斷是否需要壓縮處理 >10k 進行壓縮處理
  :param img_path:
  :return:
  """
  if img_path.endswith('.jpg') or img_path.endswith('.png'):
    size = os.path.getsize(img_path) / 1024
    if size > 10.0:
      print('文件大小:%sk' % size)
      return True
  return False


def file_loop(file_path):
  """
  遍歷文件夾
  :param file_path:
  :return:
  """
  files = os.listdir(file_path)
  for fi in files:
    fi_d = os.path.join(file_path, fi)
    if os.path.isdir(fi_d):
      file_loop(fi_d)
    else:
      child_path = os.path.join(file_path, fi_d)
      print(child_path)
      if is_need_compress(child_path):
        tiny_png(child_path)


if __name__ == "__main__":
  file_path = "/Users/lyf/AndroidStudioProjects/fubei/new-fubei-android-2.5-up/app/src/main/assets/www/assets"
  browser.get('https://tinypng.com/')
  file_loop(file_path)

改進版

優(yōu)化點:

1.遍歷完成本地文件夾再去上傳網站

2.所有圖片壓縮完成再去下載

3.啟動多線程下載

4.設定時間為加載完網絡就去上傳文件(非常非常重要,提速N倍)

import requests
from selenium import webdriver
import time
import os
import _thread
import threading
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

# browser = webdriver.Firefox(executable_path='/Users/lyf/Library/Google/geckodriver')

browser = None

image_map = {}
compress_list = []

def tiny_png(url):
  """
  打開網站進行圖片上傳下載
  :param url:
  :return:
  """
  try:
    upload_file = WebDriverWait(browser, 10).until(
      EC.presence_of_element_located((By.TAG_NAME, "input"))
    )
    upload_file.send_keys(url)
    a = WebDriverWait(browser, 20).until(
      EC.presence_of_element_located((By.LINK_TEXT, "download"))
    )
    img_url = a.get_attribute('href')
    compress_list.remove(url)
    print(img_url)
    image_map[url] = img_url
    _thread.start_new_thread(sleep, (4,))
    print('刷新網頁')
    browser.refresh()
    time.sleep(2)
  except Exception as e:
    print(e.__str__())
    browser.execute_script('window.stop()')


def sleep(delay):
  """
  一定的時間后 未加載完網頁 只要控件加載出來就可以停止網頁加載
  :param delay:
  :return:
  """
  browser.set_page_load_timeout(delay)
  browser.set_script_timeout(delay)


def down_img(file_path, down_url):
  """
  下載圖片覆蓋原地址
  :param file_path:
  :param down_url:
  :return:
  """
  r = requests.get(down_url)
  with open(file_path, 'wb') as f:
    f.write(r.content)
  print('下載完成:%s' % down_url)


def is_need_compress(img_path):
  """
  判斷是否需要壓縮處理 >10k 進行壓縮處理
  :param img_path:
  :return:
  """
  if img_path.endswith('.jpg') or img_path.endswith('.png'):
    size = os.path.getsize(img_path) / 1024
    print(img_path)
    print('文件大小:%sk' % size)
    if size > 5000.0:
      print('*****' * 30)
      print('這么大的圖片搞笑嗎')
      print(img_path)
      print('*****' * 30)
    if size > 0.0 and size < 10.0:
      return True
  return False


def file_loop(file_path, compress_list):
  """
  遍歷文件夾
  :param file_path:
  :return:
  """
  files = os.listdir(file_path)
  for fi in files:
    fi_d = os.path.join(file_path, fi)
    if os.path.isdir(fi_d):
      file_loop(fi_d, compress_list)
    else:
      child_path = os.path.join(file_path, fi_d)
      if is_need_compress(child_path):
        compress_list.append(child_path)


def down_all():
  """
  下載所有的圖片
  :return:
  """
  thread_list = []
  for k, v in image_map.items():
    print('key:%s value:%s' % (k, v))
    th = threading.Thread(target=down_img, args=(k, v))
    th.start()
    thread_list.append(th)
  for r in thread_list:
    r.join()


def loop_press():
  """
  輪詢獲取下載地址
  :return:
  """
  for url in compress_list:
    tiny_png(url)


def start_browser():
  """
  啟動瀏覽器
  :return:
  """
  global browser
  browser = webdriver.Firefox(executable_path='/Users/lyf/Library/Google/geckodriver')
  _thread.start_new_thread(sleep, (10,))
  print('加載網頁')
  try:
    browser.get('https://tinypng.com/')
  except:
    browser.execute_script('window.stop()')


if __name__ == "__main__":
  start_time = time.time()
  file_path = "/Users/lyf/Desktop/www/assets"
  # 獲取本地所有需要壓縮的圖片
  file_loop(file_path, compress_list)
  print('符合條件的圖片有%s張' % len(compress_list))
  start_browser()
  loop_press()
  while len(compress_list) > 0:
    browser.quit()
    start_browser()
    loop_press()

  # 多線程下載拿到所有返回下載的地址
  down_all()

  end = time.time()
  time_m = end - start_time
  print("time: " + str(time_m))
  browser.quit()

以上就是python如何實現圖片壓縮的詳細內容,更多關于python 圖片壓縮的資料請關注腳本之家其它相關文章!

相關文章

  • Python與C++中梯度方向直方圖的實現

    Python與C++中梯度方向直方圖的實現

    在學習HOG特征的時候,發(fā)現一片英文文章講得淺顯易懂。因此翻譯在這里學習,感興趣的朋友快來看看吧
    2022-03-03
  • python 使用cx-freeze打包程序的實現

    python 使用cx-freeze打包程序的實現

    這篇文章主要介紹了python 使用cx-freeze打包程序的實現,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • OpenCV-Python實現腐蝕與膨脹的實例

    OpenCV-Python實現腐蝕與膨脹的實例

    形態(tài)學操作主要包含:腐蝕,膨脹,開運算,閉運算,形態(tài)學梯度運算,頂帽運算,黑帽運算等操作,本文主要介紹了腐蝕與膨脹,感興趣的小伙伴們可以參考一下
    2021-06-06
  • Python計算字符寬度的方法

    Python計算字符寬度的方法

    這篇文章主要介紹了Python計算字符寬度的方法,結合實例形式較為詳細的分析了Python針對字符寬度的計算方法,需要的朋友可以參考下
    2016-06-06
  • PyTorch中Tensor的數據統計示例

    PyTorch中Tensor的數據統計示例

    今天小編就為大家分享一篇PyTorch中Tensor的數據統計示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • tensorflow+k-means聚類簡單實現貓狗圖像分類的方法

    tensorflow+k-means聚類簡單實現貓狗圖像分類的方法

    這篇文章主要介紹了tensorflow+k-means聚類簡單實現貓狗圖像分類,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • Python字符串處理實例詳解

    Python字符串處理實例詳解

    這篇文章主要介紹了Python字符串處理實例詳解的相關資料,需要的朋友可以參考下
    2017-05-05
  • Python中連接字符串的7種方法小結

    Python中連接字符串的7種方法小結

    Python?提供了將一個或多個字符串連接在一起的多種方法,本文主要介紹了Python中連接字符串的7種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-06-06
  • pygame實現方塊動畫實例講解

    pygame實現方塊動畫實例講解

    在本篇文章里小編給大家整理的是一篇關于pygame實現方塊動畫實例講解內容,以后需要的朋友們可以學習參考下。
    2021-12-12
  • python日志logging模塊使用方法分析

    python日志logging模塊使用方法分析

    這篇文章主要介紹了python日志logging模塊使用方法,結合實例形式較為詳細的分析了Python日志logging模塊相關API函數與應用技巧,需要的朋友可以參考下
    2019-05-05

最新評論