PIL学习笔记(二)

2017-11-26  本文已影响49人  oceanLong

PIL

接下来尝试,用PIL处理更微观的操作。直接处理像素点。

场景

举个例子,如果我想判断一个png图片,它是否存在alpha通道,且alpha通道的值是否全为255。因为这样的png图片整张图片不存在任何透明度,但却有Alpha通道,占用了不必要的空间,在移动端的开发中,可以进行一些压缩处理。

code

# pil pixel operation

from PIL import Image

def is_png_no_transparent(path):
    # Open file
    im = Image.open(path)
    # get image scale
    width, height = im.size
    print('Original image size: %sx%s' % (width, height))
    # for
    for w in range(0, width):
        for h in range(0, height):
            pixel = im.getpixel((w, h))
            if (isinstance(pixel ,int )):
                print "It's PNG8"
                return False
            if (len(pixel) > 3):
                if (pixel[3] != 255):
                   print "Has transparent"
                   return False
            else:
                print "It's not png "
                return False

    print "No transparent "
    return True

is_png_no_transparent("tt.png")

Tips

在PS软件中,对于png格式的处理是比较玄学的。

  1. 如果一个新的设计,图片中没有任何透明元素,当保存为png时,文件会保留着透明通道。
  2. 如果一个jpg格式的图片,被转为png,由ps保存,即使勾选保留透明通道,ps也不会为其生成透明通道。
上一篇 下一篇

猜你喜欢

热点阅读