加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python实现图片尺寸缩放脚本

发布时间:2020-12-17 07:22:19 所属栏目: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

最近由于网站对图片尺寸的需要,用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,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,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),int((x+(x * (width / height)))/2),y) 
  else: 
   region = (0,y) 
 
  #裁切图片 
  crop_img = im.crop(region) 
  #保存裁切后的图片 
  crop_img.save(cls.outfile) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:

  • python使用PIL缩放网络图片并保存的方法
  • 使用ImageMagick进行图片缩放、合成与裁剪(js+python)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读