美文网首页
更改简书图片的大小

更改简书图片的大小

作者: Andy512 | 来源:发表于2019-06-20 17:10 被阅读0次

简书的写作体验还是挺好的,编辑环境也很不错,就是商业味太浓,一天到晚都给推送关于写文章赚收入的资料,因为简书官方的这种宣传模式,导致简书用户也非常功利,写出来的东西也是空洞乏味,一看就知道是为了赚钱。

选择简书上做笔记,主要是图简书的编辑环境友好,写给自己看。但是我发现在简书上发图片,图片尺寸总是不如人意:


图片调整前

后来想到用Python写了一个自动调整图片的代码,可以把一张图片的尺寸自动调整到适合简书的大小:


图片调整后

支持批处理,效果不错:

from PIL import Image
import glob
import os
from os.path import join

class imgFORjianshu(object):
    """format the images for jianshu, including:
    changing the width and height of images
    and reduce the size of images while maintain their quality
    """
    def __init__(self, width, height, size, path):
        self.width = width
        self.height = height
        self.size = size
        self.path = path

    def _read_jpg_names(self, file_path, extenstions=['.jpg']):
        """read all of the image names from the path
        the default image format is jpg
        the image names will be shuffled
        """
        file_names = [join(file_path, fn) for fn in os.listdir(file_path)
                  if any(fn.endswith(ext) for ext in extenstions)]
        file_names = sorted(file_names)

        return file_names

    def _img_processing(self, img, img_name):
        """process imgs as required
        """
        wpercent = (self.width / float(img.size[0]))
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((self.width, hsize), Image.ANTIALIAS)
        img_name = join('./processed', img_name)
        img.save(img_name)

    def format_imgs(self, img_names=None):
        """format the images for jianshu
        """

        if img_names is None:
            extenstions = ['.png', '.jpg']
            img_list = self._read_jpg_names(file_path=self.path, extenstions=extenstions)
        else:
            img_list = img_names

        for img_fid in img_list:
            img = Image.open(img_fid)
            self._img_processing(img=img, img_name=img_fid)



if __name__ == '__main__':
    path = "./"
    test = imgFORjianshu(width=600, height=10, size=100, path=path)
    test.format_imgs()

相关文章

网友评论

      本文标题:更改简书图片的大小

      本文链接:https://www.haomeiwen.com/subject/yppjqctx.html