Python如何实现图片尺寸缩放脚本

发布时间:2021-03-23 11:38:36 作者:小新
来源:亿速云 阅读:167

这篇文章主要介绍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)

以上是“Python如何实现图片尺寸缩放脚本”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python如何实现批量按比例缩放图片效果
  2. android调用原生图片裁剪后图片尺寸缩放的解决方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:python如何实现SOM算法

下一篇:python如何实现微信发送邮件关闭电脑功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》