putpixel 实现随即色的图片
我们先用画图(mspaint) 生成 一个白板,当然 Pillow也可以生成 我们后期再说。
这么大的就行,然后保存 命名为 test.bmp 图像
开工
from PIL import Image
from random import randint
img = Image.open('test.bmp')
for w in range(200, 280): # 这里是设置图形的宽度 范围
for h in range(100 ,200): # 这里是设置图形高度 范围
r = randint(0, 255) # 取值 0-255 随机数的值 作为颜色值
g = randint(0, 255)
b = randint(0, 255)
img.putpixel((w, h), (r, g, b)) # 设置指定范围的颜色值
img.show()
结果
接下来又有了新的需求,我们需要把 这个 图像 右移 200px,且图像一致。都是随机生成的,像还原一个是基本不可能了。
思路解析:
- 将 源图像的所有像素值 获取出来,getpixel
- 获取到的像素值和位置,写到右面200px,putpixel
# 可以将 ↑ 的代码拿下来改改
for w in range(200, 280):
for h in range(100, 200):
color = img.getpixel((w, h))
img.putpixel((w + 200, h), color)
img.show()
结果
我们查看 Image 的底层源码,发现他可以支持这么多的 图像格式。
# 373
def preinit():
"""Explicitly load standard file format drivers."""
global _initialized
if _initialized >= 1:
return
try:
from . import BmpImagePlugin
assert BmpImagePlugin
except ImportError:
pass
try:
from . import GifImagePlugin
assert GifImagePlugin
except ImportError:
pass
try:
from . import JpegImagePlugin
assert JpegImagePlugin
except ImportError:
pass
try:
from . import PpmImagePlugin
assert PpmImagePlugin
except ImportError:
pass
try:
from . import PngImagePlugin
assert PngImagePlugin
except ImportError:
pass
# try:
# import TiffImagePlugin
# assert TiffImagePlugin
# except ImportError:
# pass
_initialized = 1