Python實(shí)現(xiàn)圖片尺寸縮放腳本
更新時(shí)間:2018年03月10日 17:04:40 作者:IT程序猿進(jìn)化史
這篇文章主要為大家分享了Python實(shí)現(xiàn)圖片尺寸縮放的小腳本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
最近由于網(wǎng)站對(duì)圖片尺寸的需要,用python寫(xiě)了個(gè)小腳本,方便進(jìn)行圖片尺寸的一些調(diào)整,特記錄如下:
# coding=utf-8 import Image import shutil import os class Graphics: infile = 'D:\\myimg.jpg' outfile = 'D:\\adjust_img.jpg' @classmethod def fixed_size(cls, width, height): """按照固定尺寸處理圖片""" im = Image.open(cls.infile) out = im.resize((width, height),Image.ANTIALIAS) out.save(cls.outfile) @classmethod def resize_by_width(cls, w_divide_h): """按照寬度進(jìn)行所需比例縮放""" im = Image.open(cls.infile) (x, y) = im.size x_s = x y_s = x/w_divide_h out = im.resize((x_s, y_s), Image.ANTIALIAS) out.save(cls.outfile) @classmethod def resize_by_height(cls, w_divide_h): """按照高度進(jìn)行所需比例縮放""" im = Image.open(cls.infile) (x, y) = im.size x_s = y*w_divide_h y_s = y out = im.resize((x_s, y_s), Image.ANTIALIAS) out.save(cls.outfile) @classmethod def resize_by_size(cls, size): """按照生成圖片文件大小進(jìn)行處理(單位KB)""" size *= 1024 im = Image.open(cls.infile) size_tmp = os.path.getsize(cls.infile) q = 100 while size_tmp > size and q > 0: print q out = im.resize(im.size, Image.ANTIALIAS) out.save(cls.outfile, quality=q) size_tmp = os.path.getsize(cls.outfile) q -= 5 if q == 100: shutil.copy(cls.infile, cls.outfile) @classmethod def cut_by_ratio(cls, width, height): """按照?qǐng)D片長(zhǎng)寬比進(jìn)行分割""" im = Image.open(cls.infile) width = float(width) height = float(height) (x, y) = im.size if width > height: region = (0, int((y-(y * (height / width)))/2), x, int((y+(y * (height / width)))/2)) elif width < height: region = (int((x-(x * (width / height)))/2), 0, int((x+(x * (width / height)))/2), y) else: region = (0, 0, x, y) #裁切圖片 crop_img = im.crop(region) #保存裁切后的圖片 crop_img.save(cls.outfile)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Tensorflow 實(shí)現(xiàn)釋放內(nèi)存
今天小編就為大家分享一篇Tensorflow 實(shí)現(xiàn)釋放內(nèi)存,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02python hash每次調(diào)用結(jié)果不同的原因
這篇文章主要介紹了python hash每次調(diào)用結(jié)果不同的原因,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11解決Pandas to_json()中文亂碼,轉(zhuǎn)化為json數(shù)組的問(wèn)題
今天小編就為大家分享一篇解決Pandas to_json() 中文亂碼,轉(zhuǎn)化為json數(shù)組的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05Windows下安裝python2和python3多版本教程
這篇文章主要介紹下Windows(我用的Win10)環(huán)境下的python2.x 和 python3.x 的安裝,以及python2.x 與 python3.x 共存時(shí)的配置問(wèn)題。2017-03-03pip版本低引發(fā)的python離線(xiàn)包安裝失敗的問(wèn)題
這篇文章主要介紹了pip版本低引發(fā)的python離線(xiàn)包安裝失敗的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09