[Pillow]-Reference-Image Module-

2021-08-05  本文已影响0人  六千宛

Image.new(mode, size, color=0)

Image.new(mode, size, color=0):根据模式、大小和颜色创建一个新的Image对象。
mode:用于新图像的模式。支持的模式请看下方Pillow支持的模式表
size: 大小,元组类型,包含宽度与高度
color:用于新图像的颜色。传入一个整数的单波段模式,或传入一个元组的多波段模式,或者传入一个ImageColor对象

from PIL import Image
# 单个整数值
img = Image.new("RGBA",(1024,768),215)
# 元组
img = Image.new("RGBA",(1024,768),(215,0,0)
# ImageColor
from PIL import ImageColor
color = ImageColor.getrgb("#FF0000")
img = Image.new("RGBA",(1024,768),color)
img.show()

Image.fromarray(obj,mode=None)

def fromarray(obj, mode=None):
    """
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol).
    从导出阵列接口的对象创建图像存储器
     (使用缓冲协议)。

    If **obj** is not contiguous, then the tobytes method is called
    and :py:func:`~PIL.Image.frombuffer` is used.
    如果** obj **不连续,则调用tobytes方法
     和:py:func:`〜PIL.Image.frombuffer`被使用。

    If you have an image in NumPy::

      from PIL import Image
      import numpy as np
      im = Image.open('hopper.jpg')
      a = np.asarray(im)

    Then this can be used to convert it to a Pillow image::

      im = Image.fromarray(a)

    :param obj: Object with array interface
    :param mode: Mode to use (will be determined from type if None)
      See: :ref:`concept-modes`.
    :returns: An image object.

    .. versionadded:: 1.1.6
    """
    arr = obj.__array_interface__
    shape = arr['shape']
    ndim = len(shape)
    strides = arr.get('strides', None)
    if mode is None:
        try:
            typekey = (1, 1) + shape[2:], arr['typestr']
            mode, rawmode = _fromarray_typemap[typekey]
        except KeyError:
            raise TypeError("Cannot handle this data type")
    else:
        rawmode = mode
    if mode in ["1", "L", "I", "P", "F"]:
        ndmax = 2
    elif mode == "RGB":
        ndmax = 3
    else:
        ndmax = 4
    if ndim > ndmax:
        raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))

    size = shape[1], shape[0]
    if strides is not None:
        if hasattr(obj, 'tobytes'):
            obj = obj.tobytes()
        else:
            obj = obj.tostring()

    return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)

PIL.Image.frombytes(mode, size, data, decoder_name='raw', *args)

# 示例代码
import requests
from PIL import Image
content = requests.get("http://my.cnki.net/Register/CheckCode.aspx?id=1563416120154").content
image = Image.frombytes(mode="RGBA",size=(64,25),data=content,decoder_name="raw")

会抛出异常

ValueError: not enough image data

经查找资料(https://stackoverflow.com/questions/8328198/pil-valueerror-not-enough-image-data) 得知该图片为jpg格式,包括了图片的原始(jpg压缩后的)数据和(jpg)文件头,而frombytes只能读取纯二进制数据

修改方案

from io import StringIO,BytesIO
import requests
from PIL import Image
content = requests.get("http://my.cnki.net/Register/CheckCode.aspx?id=1563416120154").content
image = Image.open(BytesIO(content))

将Image对象转成bytes或者BytesIO

 imgByteArr = BytesIO()
 image.save(imgByteArr,format="PNG")
 imgByteArr.getvalue()

Image.frombuffer(mode, size, data, decoder_name='raw', *args)

參數:
mode-圖像模式。
size-圖像尺寸。
data-包含給定模式原始數據的字節緩衝區。
decoder_name-使用什麽解碼器。
args-給定解碼器的其他參數。對於默認編碼器(“raw”),建議完整的參數集:frombuffer(mode, size, data, "raw", mode, 0, 1)

# importing image object from PIL 
from PIL import Image 
  
# creating an image object 
im = Image.open(r"C:\Users\System-Pc\Desktop\rose.jpg") 
im1 = im.tobytes("xbm", "rgb") 
img = Image.frombuffer("L", (4, 4), im1, 'raw', "L", 0, 1) 
  
# creating list  
img2 = list(img.getdata()) 
print(img2)

输出

[48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48]
上一篇下一篇

猜你喜欢

热点阅读