0

我有一个包含颜色名称和值的文件

foo,(255, 212, 201),#FFD4C9
bar,(248, 201, 189),#F8C9BD
baz,(167, 145, 138),#A7918A

我想变成 200px × 200px 的色板(即只是那种颜色的矩形),命名为foo.gif,bar.gif等。我尝试Wand在 Python 3 中这样做,但我没有运气。

SIZE = 200
with open("foo.txt") as f:
    for line in f:
        if line[0] != "#":
            (name, _, hex_color) = tuple(line.strip().split(","))
            hex_color = hex_color.lower()
            print("{}, {}".format(name, hex_color))

            image_name = "{}.gif".format(name)
            with Drawing() as draw:
                # set draw.fill_color here?
                draw.rectangle(left=0, top=0, width=SIZE, height=SIZE)
                with Image() as image:
                    draw(image)
                    image.format = 'gif'
                    image.save(filename=image_name)

给我

Traceback (most recent call last):
  File "color_swatches.py", line 36, in <module>
    image.format = 'PNG'
  File "/usr/local/lib/python3.4/site-packages/wand/image.py", line 2101, in format
    raise ValueError(repr(fmt) + ' is unsupported format')
ValueError: 'gif' is unsupported format

我也尝试另存为jpeg, jpg, png, 并PNG无济于事。也许我在凌晨四点半做这件事是罪魁祸首。


编辑:我能够使用以下bash脚本完成任务,

#!/bin/bash
while IFS=, read name _ hex
do
    convert -size 200x200 xc:white -fill $hex -draw "rectangle 0,0 200,200" \
        swatches/$name.gif
done < $1

但我仍然很好奇我做错了什么Wand。基于我遇到的省略xc:<color>导致bash脚本失败的问题,我认为添加一行

image.background_color = Color("#fff")

行之后with Image() as image:可能会起作用,但是,我收到一个新错误:

Traceback (most recent call last):
  File "color_swatches.py", line 38, in <module>
    image.background_color = Color("#fff")
  File "/usr/local/lib/python3.4/site-packages/wand/image.py", line 419, in wrapped
    result = function(self, *args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/wand/image.py", line 1021, in background_color
    self.raise_exception()
  File "/usr/local/lib/python3.4/site-packages/wand/resource.py", line 218, in raise_exception
    raise e
wand.exceptions.WandError: b"wand contains no images `MagickWand-2' @ error/magick-image.c/MagickSetImageBackgroundColor/9541"
4

1 回答 1

1

第一个错误有点误导,但第二个消息是正确的。您的Image()构造函数分配了 wand 对象,但没有分配新图像。与您的 bash 脚本调用方式相同,-size 200x200您需要定义width=& height=in Image()

with Drawing() as draw:
  # set draw.fill_color here? YES
  draw.fill_color = Color(hex_color)
  draw.rectangle(left=0, top=0, width=SIZE, height=SIZE)
  with Image(width=SIZE,height=SIZE) as image:
    draw(image)
    image.format = 'gif'
    image.save(filename=image_name)
于 2014-09-12T17:10:12.563 回答