Python实现图片尺寸缩放脚本

yipeiwu_com6年前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写的Tkinter程序屏幕居中方法

本文适用场景:想用Tkinter开发界面程序并屏幕居中,但没找到相应的API。 这两天玩了玩Tkinter,感觉不错,就是屏幕居中这个问题在网上搜了很长时间也没 找到答案,最后没办法,...

Python中常用的8种字符串操作方法

Python中常用的8种字符串操作方法

拼接字符串 使用“+”可以对多个字符串进行拼接 语法格式: str1 + str2 >>> str1 = "aaa" >>> str2 = "b...

python的pdb调试命令的命令整理及实例

python的pdb调试命令的命令整理及实例 一、命令整理 pdb调试命令 完整命令 简写命令 描述...

Python中处理字符串之islower()方法的使用简介

 islower()方法判断检查字符串的所有的字符(字母)是否为小写。 语法 以下是islower()方法的语法: str.islower() 参数  ...

python 读取视频,处理后,实时计算帧数fps的方法

实时计算每秒的帧数 cap = cv2.VideoCapture("DJI_0008.MOV") #cap = cv2.VideoCapture(0) # Define the...