Python 生成纯色或渐变色图片

1.问题或需求描述:

Python 生成纯色或渐变色图片

2.解决方法或原理:

python 代码

import numpy as np
from PIL import Image

def RGB(r,g,b): return (r,g,b)

def Make_img_data(width, height, rgb):
    '''Make image data'''
    result = np.zeros((height, width, 3), dtype=np.uint8)
    for i, v in enumerate(rgb):
        result[:,:,i] = np.tile(np.linspace(v, v, width), (height, 1))

    return result

def Make_gradation_img_data(width, height, rgb_start, rgb_stop, horizontal=(True, True, True)):
    '''Make gradation image data'''
    result = np.zeros((height, width, 3), dtype=np.uint8)
    for i, (m,n,o) in enumerate(zip(rgb_start, rgb_stop, horizontal)):
        if o:
            result[:,:,i] = np.tile(np.linspace(m, n, width), (height, 1))
        else:
            result[:,:,i] = np.tile(np.linspace(m, n, width), (height, 1)).T

    return result

MakeImg = lambda width, height, rgb: Image.fromarray(Make_img_data(width, height, rgb))

MakeGradationImg = lambda width, height, rgb_start, rgb_stop, horizontal=(True, True, True): \
    Image.fromarray(Make_gradation_img_data(width, height, rgb_start, rgb_stop, horizontal))

#Function Test
img = MakeImg(400, 400, RGB(255,0,0))   #red
img.save('red.png')
#~ img.show()

img = MakeImg(400, 400, RGB(0,255,0))   #green
img.save('green.png')
#~ img.show()

img = MakeImg(400, 400, RGB(0,0,255))   #blue
img.save('blue.png')
#~ img.show()

img = MakeGradationImg(400, 400, RGB(255,0,0), RGB(0,255,0), (True, True, True))
img.save('img_001.png')
#~ img.show()

img = MakeGradationImg(400, 400, RGB(255,0,0), RGB(0,255,0), (False, True, True))
img.save('img_002.png')
#~ img.show()

img = MakeGradationImg(400, 400, RGB(255,0,0), RGB(0,255,0), (False, False, True))
img.save('img_003.png')
#~ img.show()

img = MakeGradationImg(400, 400, RGB(255,0,0), RGB(0,255,0), (False, False, False))
img.save('img_004.png')
#~ img.show()

3.运行结果

1.red.png:
Python 生成纯色或渐变色图片
2.green.png:
Python 生成纯色或渐变色图片
3.blue.png:
Python 生成纯色或渐变色图片
4.img_001.png:
Python 生成纯色或渐变色图片
5.img_002.png:
Python 生成纯色或渐变色图片
6.img_003.png:
Python 生成纯色或渐变色图片
7.img_004.png:
Python 生成纯色或渐变色图片

猜你喜欢

转载自blog.51cto.com/firswof/2551047