我有一个由颜色、名称和值组成的文件。
foo,(255, 212, 201),#FFD4C9
bar,(248, 201, 189),#F8C9BD
baz,(167, 145, 138),#A7918A我想把它变成200‘m×200’m色块(也就是那个颜色的矩形),名为foo.gif,bar.gif等等。我尝试用Python 3中的Wand来做这件事,但是我没有运气。
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,但都没有效果。也许是我在凌晨4点25分做这件事的原因。
编辑:我能够用下面的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"发布于 2014-09-12 17:10:12
第一个错误有点误导,但第二个信息是正确的。Image()构造函数分配魔杖对象,但不分配新图像。正如bash脚本调用-size 200x200一样,您需要在Image()中定义width= & height=。
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)https://stackoverflow.com/questions/25445155
复制相似问题