首页 > 编程语言 > 详细

Python 生成纯色或渐变色图片

时间:2020-11-16 09:45:34      阅读:107      评论:0      收藏:0      [点我收藏+]
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:
技术分享图片
2.green.png:
技术分享图片
3.blue.png:
技术分享图片
4.img_001.png:
技术分享图片
5.img_002.png:
技术分享图片
6.img_003.png:
技术分享图片
7.img_004.png:
技术分享图片

Python 生成纯色或渐变色图片

原文:https://blog.51cto.com/firswof/2551047

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!