Python 图片尺寸缩放的4种方式

 

微信公众号" 程序猿刘先森", 共同学习~

 

https://darylliu.github.io/archives/9c4cfe08.html

 

 

最近由于网站对图片尺寸的需要,用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)

 

 

 

http://www.darylliu.cn/archives/9c4cfe08.html

微信公众号" 程序猿刘先森", 共同学习进化~

 

 

  • 38
    点赞
  • 70
    收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 4

打赏作者

公众号-程序猿刘先森

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值