Python 生成純色或漸變色圖片python
python 代碼ide
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()
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:
ui