【问题标题】:Two-color linear gradient positioning with PIL Python使用 PIL Python 进行双色线性渐变定位
【发布时间】:2021-08-31 19:13:09
【问题描述】:

也许这对许多人来说很容易。 我正在尝试从 2 种颜色创建背景。其目的是它以一种颜色从左侧开始,在右侧(水平方向)以另一种颜色结束。

问题是我从一个角落到另一个角落。而我正在寻找的是它是并排的。

我的代码:

from PIL import Image, ImageDraw

def interpolate(f_co, t_co, interval):
    det_co =[(t - f) / interval for f , t in zip(f_co, t_co)]
    for i in range(interval):
        yield [round(f + det * i) for f, det in zip(f_co, det_co)]


imgsize=(1920,1080)
gradient = Image.new('RGBA', imgsize, color=0)
draw = ImageDraw.Draw(gradient)

f_co = (253, 46, 216)
t_co = (23, 214, 255)
for i, color in enumerate(interpolate(f_co, t_co, gradient.width * 2)):
    draw.line([(i, 0), (0, i)], tuple(color), width=1)
gradient.show()

结果:https://i.imgur.com/p5slKTg.png

【问题讨论】:

  • 从左到右?
  • 是的,就是这样

标签: python python-imaging-library gradient


【解决方案1】:

对于从左到右,最简单的解决方法是修改 draw.line 坐标

draw.line([(i, 0), (0, i)], tuple(color), width=1)

draw.line([(i, 0), (i, gradient.height)], tuple(color), width=1)

并将interpolate() 调用中的gradient.width * 2 调整为仅gradient.width。 结果是

从上到下,您需要将参数调整为 interpolate() 以使用 gradient.height 并执行

draw.line([(0, i), (gradient.width, i)], tuple(color), width=1)

结果是

【讨论】:

  • 非常感谢你正是我所需要的我已经尝试投票支持你的帮助,但它需要 15 声望。当我得到它时,我会给你积极的按钮
【解决方案2】:

我想我会采取不同的方法,而不是画 3,840 条线:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define start and end colours and image height and width
colourA=[255, 0, 255]
colourB=[0, 255, 255]
h, w = 1080, 1920

# Make output image
gradient = np.zeros((h,w,3), np.uint8)

# Fill R, G and B channels with linear gradient between two end colours
gradient[:,:,0] = np.linspace(colourA[0], colourB[0], w, dtype=np.uint8)
gradient[:,:,1] = np.linspace(colourA[1], colourB[1], w, dtype=np.uint8)
gradient[:,:,2] = np.linspace(colourA[2], colourB[2], w, dtype=np.uint8)

# Save result
Image.fromarray(gradient).save('result.png')

【讨论】:

  • 这肯定会更快,但与 OP 的原始方法相去甚远(并且难以适应任意角度):)
  • 如果两面之一是透明的?假设它会变成一种颜色,直到它变得完全透明
  • 您也可以轻松添加渐变透明度。只需在颜色中添加第 4 个元素,使其为 RGBA 而不是 RGB,使用 gradient = np.zeros((h,w,4), np.uint8) 将结果设为 4 通道,并添加额外的一行以在 alpha 通道中创建线性渐变 gradient[:,:,3] = np.linspace(colourA[3], colourB[3], w, dtype=np.uint8)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 2012-07-04
  • 2022-12-15
  • 1970-01-01
  • 2015-06-05
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多