用python画渐变的圆,在Python中使用PIL绘制圆形渐变

I'm creating images using Python, using

myImage = Image.new('RGB', (250, 250), 'rgb(155,89,182)')

and this actually creates the image. But is there a way to create an image with a background of the color I'm choosing but with gradients? I want to pick blue as my color, then, I want deep blue in the edges and more light blue in the center of the image. Is that possible using simple PIL and Python?

Thank you in advance.

解决方案

The code depends on how you want the gradient to look.

You could make it a rectangular gradient which would look like this:

mejyh.jpg

Or you could make it a round gradient like this:

vOyv2.jpg

This would be the code for the round gradient:

import Image

import math

imgsize = (250, 250) #The size of the image

image = Image.new('RGB', imgsize) #Create the image

innerColor = [80, 80, 255] #Color at the center

outerColor = [0, 0, 80] #Color at the corners

for y in range(imgsize[1]):

for x in range(imgsize[0]):

#Find the distance to the center

distanceToCenter = math.sqrt((x - imgsize[0]/2) ** 2 + (y - imgsize[1]/2) ** 2)

#Make it on a scale from 0 to 1

distanceToCenter = float(distanceToCenter) / (math.sqrt(2) * imgsize[0]/2)

#Calculate r, g, and b values

r = outerColor[0] * distanceToCenter + innerColor[0] * (1 - distanceToCenter)

g = outerColor[1] * distanceToCenter + innerColor[1] * (1 - distanceToCenter)

b = outerColor[2] * distanceToCenter + innerColor[2] * (1 - distanceToCenter)

#Place the pixel

image.putpixel((x, y), (int(r), int(g), int(b)))

image.save('circlegradient.jpg')

For each pixel, it sets the red, green, and blue values somewhere in between innerColor and outerColor depending on the distance from the pixel to the center.

This would be the code for the rectangular gradient:

import Image

imgsize = (250, 250) #The size of the image

image = Image.new('RGB', imgsize) #Create the image

innerColor = [80, 80, 255] #Color at the center

outerColor = [0, 0, 80] #Color at the edge

for y in range(imgsize[1]):

for x in range(imgsize[0]):

#Find the distance to the closest edge

distanceToEdge = min(abs(x - imgsize[0]), x, abs(y - imgsize[1]), y)

#Make it on a scale from 0 to 1

distanceToEdge = float(distanceToEdge) / (imgsize[0]/2)

#Calculate r, g, and b values

r = innerColor[0] * distanceToEdge + outerColor[0] * (1 - distanceToEdge)

g = innerColor[1] * distanceToEdge + outerColor[1] * (1 - distanceToEdge)

b = innerColor[2] * distanceToEdge + outerColor[2] * (1 - distanceToEdge)

#Place the pixel

image.putpixel((x, y), (int(r), int(g), int(b)))

image.save('rectgradient.jpg')

This works the same way, except it measures the distance to the closest edge, not the center.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值