Python實現圖片尺寸縮放指令碼,

來源:互聯網
上載者:User

Python實現圖片尺寸縮放指令碼,

最近由於網站對圖片尺寸的需要,用python寫了個小指令碼,方便進行圖片尺寸的一些調整,特記錄如下:

# 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):   """按照寬度進行所需比例縮放"""   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):   """按照高度進行所需比例縮放"""   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):   """按照產生圖片檔案大小進行處理(單位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):   """按照圖片長寬比進行分割"""   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) 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.