Python实现图片尺寸缩放脚本

yipeiwu_com5年前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设计】。

相关文章

Python&&GDAL实现NDVI的计算方式

Python&&GDAL实现NDVI的计算方式

很短的几句代码,可是我却花了很长的时间才写出来,因为array那里的除法运算结果老是不对,正常在-1-1之间的。从别的资料摘来处理NDVI计算的array代码处,出现了很多问题,可能它用...

Python命令行参数解析工具 docopt 安装和应用过程详解

什么是 docopt? 1、docopt 是一种 Python 编写的命令行执行脚本的交互语言。 它是一种语言! 它是一种语言! 它是一种语言! 2、使用这种语言可以在自己的脚本中,添...

python 实现查找文件并输出满足某一条件的数据项方法

python 实现文件查找和某些项输出 本文是基于给定一文件(students.txt),查找其中GPA分数最高的 输出,同时输出其对应的姓名和学分 一. 思路 首先需要打开文件,读取文...

python 数字类型和字符串类型的相互转换实例

一、python中字符串转换成数字 (方法1) 类中进行导入:import string str='555' num=string.atoi(str) num即为str转换成的数字...

PyCharm专业最新版2019.1安装步骤(含激活码)

PyCharm专业最新版2019.1安装步骤(含激活码)

Pycharm是一款很好用的python开发工具,开发Python爬虫和Python web方面都很不错 这里我为大家提供了两种pycharm激活方式 分别为:2020年、2089年、...