ImageDraw.Draw( )对象画长方形
时间: 2023-05-28 14:05:55 浏览: 201
以下是使用ImageDraw.Draw()对象画长方形的示例代码:
```
from PIL import Image, ImageDraw
# 创建一个空白图像
img = Image.new("RGB", (400, 400), "white")
# 创建一个ImageDraw.Draw()对象
draw = ImageDraw.Draw(img)
# 画一个红色长方形
draw.rectangle((100, 100, 300, 300), fill="red")
# 保存图像
img.save("rectangle.png")
```
在上述代码中,我们首先创建了一个空白的图像,并创建了一个ImageDraw.Draw()对象。然后,我们使用该对象的rectangle()方法画了一个红色长方形,并将图像保存为PNG文件。长方形的坐标参数是一个四元组,分别表示左上角和右下角的坐标。在本例中,我们将长方形的左上角坐标设置为(100, 100),右下角坐标设置为(300, 300)。
相关问题
ImageDraw.Draw( )对象画长方形线框
以下是使用ImageDraw.Draw()对象画长方形线框的Python代码示例:
```python
from PIL import Image, ImageDraw
# 创建一个空白图像
img = Image.new('RGB', (500, 500), color='white')
# 创建一个ImageDraw.Draw()对象
draw = ImageDraw.Draw(img)
# 画长方形线框
draw.rectangle((50, 50, 200, 150), outline='black')
# 显示图像
img.show()
```
在上面的代码中,我们首先创建了一个空白图像,然后创建了一个ImageDraw.Draw()对象。接下来,我们使用draw.rectangle()方法画了一个长方形线框,该方法的参数是一个元组,表示长方形的坐标(左上角和右下角的坐标)。最后,我们使用img.show()方法显示图像。
import os from PIL import Image, ImageDraw def hex_to_rgb(hex_color): """ Convert a hexadecimal color string to an RGB tuple """ h = hex_color.lstrip('#') return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) def ensure_directory_exists(directory_path): if not os.path.exists(directory_path): os.makedirs(directory_path) def draw_colors_as_image(colors_list, output_dir=r'C:\COLOR\color-extraction-main\color-extraction-main\imgs\blog\kmeans\out', filename_prefix='output'): bar_width = 100 height = 100 # Ensure that the directory exists before saving images there. ensure_directory_exists(output_dir) # Iterate over each list of colors and produce corresponding image files. for idx, colors in enumerate(colors_list): img_width = len(colors) * bar_width # Create blank white image with the specified dimensions. im = Image.new("RGB", (img_width, height), "white") drawer = ImageDraw.Draw(im) x_offset = 0 for c in colors: rgb_c = hex_to_rgb(c) drawer.rectangle([x_offset, 0, x_offset + bar_width - 1, height], fill=rgb_c, outline=(0, 0, 0)) x_offset += bar_width output_filename = f"{filename_prefix}_{idx + 1}.png" full_output_path = os.path.join(output_dir, output_filename) print(f'Saving {full_output_path}...') im.save(full_output_path) if __name__ == '__main__': input_data = [ ["#0c0e1e", "#bab2a6", "#5a5e65", "#263448"], ["#4c4148", "#75b2b1", "#d2d2d1", "#a2a1a2"], ["#393144", "#d5bba7", "#9b5c69", "#d29370"], ["#4e1c2f", "#a11227", "#c21b2a", "#c95e28"], ["#aba599", "#d9dad1", "#675e52", "#552f1e"], ["#dbd5d1", "#9f5944", "#d5ae3d", "#231d1c"] ] draw_colors_as_image(input_data, output_dir=r'C:\COLOR\color-extraction-main\color-extraction-main\imgs\blog\kmeans\out', filename_prefix=' ')这是(MAIN.PY)
这段 Python 代码的主要功能是将一组颜色值(以十六进制字符串表示)转换成图像,并将这些图像保存到指定的输出目录中。接下来,我会详细介绍各个部分的功能及其工作原理。
### 导入所需模块
```python
import os
from PIL import Image, ImageDraw
```
这里导入了两个必要的库:
- `os`: 提供操作系统级别的交互能力,主要用于检查和创建文件夹。
- `PIL.Image`, `PIL.ImageDraw`: 来自 Pillow 库,提供强大的图像处理功能,允许我们创建新图像并在上面绘制图形。
### 辅助函数定义
#### hex_to_rgb()
```python
def hex_to_rgb(hex_color):
""" Convert a hexadecimal color string to an RGB tuple """
h = hex_color.lstrip('#')
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
```
此函数接受一个以 `#` 开头的十六进制颜色串作为输入,并将其解析为一个 `(R, G, B)` 的元组,方便后续在图像上应用具体的色彩配置。
#### ensure_directory_exists()
```python
def ensure_directory_exists(directory_path):
if not os.path.exists(directory_path):
os.makedirs(directory_path)
```
确保给定路径下的文件夹存在。如果不存在,则递归地创建它。这一步非常重要,因为在保存生成的图像之前需要确认目标位置已经准备好。
### 核心逻辑:draw_colors_as_image()
这个函数负责接收一系列的颜色列表并将它们渲染成条形图样的 PNG 文件,同时控制每个矩形的高度宽度等属性:
- 参数描述:
- `colors_list`: 需要可视化的颜色集合,其中每一个元素都是一个包含多个十六进制颜色字符串的列表;
- `output_dir`: 输出图像存放的目标文件夹绝对路径,默认指向项目内的某一固定子目录;
- `filename_prefix`: 为导出的所有图像名称添加前缀,默认为空格字符 `' '`。
核心流程如下:
1. **确定输出目录是否存在**并通过调用辅助函数保证其可用性;
2. 迭代遍历传入的每一种配色方案,在每次迭代过程中动态计算合成图像的整体尺寸 (`img_width`);
3. **初始化空白底板**: 创建一块白色背景的新画布,并获取与之关联的一个绘画对象 (`drawer`);
4. 再次逐一对比内部的颜色项,依次填充水平排列的一系列竖直长方形区域,采用从左向右逐步偏移的方式实现相邻色块之间的拼接效果;
5. 构造完整的文件名并且打印提示信息告知用户正在保存哪一个资源;
6. 使用 Pillow API 实现位图的实际落地存储操作。
### 入口检测与示例运行
```python
if __name__ == '__main__':
input_data = [
["#0c0e1e", "#bab2a6", "#5a5e65", "#263448"],
// ... 更多颜色组合省略 ...
["#dbd5d1", "#9f5944", "#d5ae3d", "#231d1c"]
]
draw_colors_as_image(input_data,
output_dir=r'C:\COLOR\color-extraction-main\color-extraction-main\imgs\blog\kmeans\out',
filename_prefix=' ')
```
当直接执行该脚本时会触发这一段主程序入口处的条件判断分支。它首先准备了一套预设好的颜色样本集 `input_data` ,随后调用了前面定义的核心绘图方法对其进行加工处理。
---
阅读全文
相关推荐










