内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

python實現(xiàn)無損批量壓縮圖片-創(chuàng)新互聯(lián)

python 實現(xiàn)無損批量壓縮圖片?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

創(chuàng)新互聯(lián)一直在為企業(yè)提供服務(wù),多年的磨煉,使我們在創(chuàng)意設(shè)計,成都全網(wǎng)營銷推廣到技術(shù)研發(fā)擁有了開發(fā)經(jīng)驗。我們擅長傾聽企業(yè)需求,挖掘用戶對產(chǎn)品需求服務(wù)價值,為企業(yè)制作有用的創(chuàng)意設(shè)計體驗。核心團隊擁有超過十余年以上行業(yè)經(jīng)驗,涵蓋創(chuàng)意,策化,開發(fā)等專業(yè)領(lǐng)域,公司涉及領(lǐng)域有基礎(chǔ)互聯(lián)網(wǎng)服務(wù)西信服務(wù)器托管、成都App定制開發(fā)、手機移動建站、網(wǎng)頁設(shè)計、網(wǎng)絡(luò)整合營銷。

1、批量壓縮照片

新建 photo_compress.py 代碼如下

# -*- 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):
 """獲取文件目錄通用函數(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'開始下載文件 :%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個線程執(zhí)行此任務(wù)
 download_thread_pool = ThreadPoolExecutor(10) # 定義5個線程執(zhí)行此任務(wù)
 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實現(xiàn)無損批量壓縮圖片-創(chuàng)新互聯(lián)
分享鏈接:http://m.rwnh.cn/article0/ggeoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站制作、關(guān)鍵詞優(yōu)化、自適應(yīng)網(wǎng)站、靜態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司
辉南县| 桃园市| 黑山县| 栾城县| 宁晋县| 社旗县| 新乐市| 衡阳县| 孟津县| 古田县| 成武县| 九江县| 独山县| 陈巴尔虎旗| 清远市| 茂名市| 奎屯市| 高台县| 昭觉县| 南开区| 永嘉县| 涞水县| 荆州市| 井冈山市| 京山县| 抚顺县| 泽库县| 柳州市| 开平市| 西藏| 珠海市| 香河县| 长春市| 修武县| 梨树县| 盘山县| 安阳市| 信丰县| 调兵山市| 武陟县| 桃园县|