上犹电脑信息网我们一直在努力
您的位置:上犹电脑信息网 > 电脑怎么了 > 照片怎么缩小-Python 图片尺寸缩放的4种方式

照片怎么缩小-Python 图片尺寸缩放的4种方式

作者:上犹日期:

返回目录:电脑怎么了

最近由于网站对图片尺寸的需要,用python写了个小脚本,方便进行图片尺寸的一些调整,特记录如下:



  1. # coding=utf-8
  2. import Image
  3. import shutil
  4. import os
  5. class Graphics:
  6. infile = 'D:myimg.jpg'
  7. outfile = 'D:adjust_img.jpg'
  8. @classmethod
  9. def fixed_size(cls, width, height):
  10. """按照固定尺寸处理图片"""
  11. im = Image.open(cls.infile)
  12. out = im.resize((width, height),Image.ANTIALIAS)
  13. out.save(cls.outfile)
  14. @classmethod
  15. def resize_by_width(cls, w_divide_h):
  16. """按照宽度进行所需比例缩放"""
  17. im = Image.open(cls.infile)
  18. (x, y) = im.size
  19. x_s = x
  20. y_s = x/w_divide_h
  21. out = im.resize((x_s, y_s), Image.ANTIALIAS)
  22. out.save(cls.outfile)
  23. @classmethod
  24. def resize_by_height(cls, w_divide_h):
  25. """按照高度进行所需比例缩放"""
  26. im = Image.open(cls.infile)
  27. (x, y) = im.size
  28. x_s = y*w_divide_h
  29. y_s = y
  30. out = im.resize((x_s, y_s), Image.ANTIALIAS)
  31. out.save(cls.outfile)
  32. @classmethod
  33. def resize_by_size(cls, size):
  34. """按照生成图片文件大小进行处理(单位KB)"""
  35. size *= 1024
  36. im = Image.open(cls.infile)
  37. size_tmp = os.path.getsize(cls.infile)
  38. q = 100
  39. while size_tmp > size and q > 0:
  40. print q
  41. out = im.resize(im.size, Image.ANTIALIAS)
  42. out.save(cls.outfile, quality=q)
  43. size_tmp = os.path.getsize(cls.outfile)
  44. q -= 5
  45. if q == 100:
  46. shutil.copy(cls.infile, cls.outfile)
  47. @classmethod
  48. def cut_by_ratio(cls, width, height):
  49. """按照图片长宽比进行分割"""
  50. im = Image.open(cls.infile)
  51. width = float(width)
  52. height = float(height)
  53. (x, y) = im.size
  54. if width > height:
  55. region = (0, int((y-(y * (height / width)))/2), x, int((y+(y * (height / width)))/2))
  56. elif width < height:
  57. region = (int((x-(x * (width / height)))/2), 0, int((x+(x * (width / height)))/2), y)
  58. else:
  59. region = (0, 0, x, y)
  60. #裁切图片
  61. crop_img = im.crop(region)
  62. #保存裁切后的图片
  63. crop_img.save(cls.outfile)

相关阅读

关键词不能为空
极力推荐

电脑蓝屏_电脑怎么了_win7问题_win10问题_设置问题_文件问题_上犹电脑信息网

关于我们