You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PIL生成500x500像素指定颜色随机分布的图像

实现方案

直接用PIL逐块填充预设颜色池内的随机色即可,生成的RGB模式图像可以直接对接pygame的fromstring方法,不需要额外格式转换。

前置依赖

先安装需要的第三方库:
pip install pillow pygame

完整实现代码

import random
from PIL import Image
import pygame

# 基础配置
IMAGE_SIZE = (500, 500)
# 自定义允许使用的颜色集合,RGB格式,可按需增删
ALLOWED_COLORS = [
    (255, 0, 0),   # 红色
    (0, 0, 255),   # 蓝色
    (255, 255, 0)  # 黄色
]
# 色块尺寸,值为1时是单像素噪点效果(和参考效果一致),数值越大大色块尺寸越大
BLOCK_SIZE = 1

# 生成PIL图像
img = Image.new('RGB', IMAGE_SIZE)
pixel_access = img.load()
width, height = IMAGE_SIZE

# 遍历位置填充随机颜色
for y_start in range(0, height, BLOCK_SIZE):
    for x_start in range(0, width, BLOCK_SIZE):
        current_color = random.choice(ALLOWED_COLORS)
        # 填充当前色块覆盖的所有像素
        for y in range(y_start, min(y_start + BLOCK_SIZE, height)):
            for x in range(x_start, min(x_start + BLOCK_SIZE, width)):
                pixel_access[x, y] = current_color

# 转换为pygame可用的Surface对象
pygame_surface = pygame.image.fromstring(img.tobytes(), IMAGE_SIZE, 'RGB')

# 以下是测试显示代码,正式集成时可删除
pygame.init()
screen = pygame.display.set_mode(IMAGE_SIZE)
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.blit(pygame_surface, (0, 0))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

注意事项

  • 不要修改PIL创建图像时的'RGB'模式和pygame转换时的'RGB'格式参数,两者一一对应,能避免颜色错位、花屏问题
  • 调整BLOCK_SIZE参数可以控制色块大小,比如设置为20就会生成20*20像素的大方块随机排布效果
  • ALLOWED_COLORS列表可以自由修改,添加任意你需要的RGB颜色值即可,没有数量限制
  • 代码默认生成500*500尺寸的图像,完全匹配需求,后续如果要调整尺寸只需要修改IMAGE_SIZE的值

内容的提问来源于stack exchange,提问作者Mashu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 22:48:36