Python 3和Wand:尝试保存新图像时的ValueError

时间:2014-08-22 10:43:09

标签: python-3.x wand

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

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

我想变成200px×200px的颜色样本(即只有那种颜色的矩形),名为foo.gifbar.gif等。我试图用{{1在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 jpegjpgpng无济于事。也许我早上四分之一到四点这样做是值得责备的。


编辑:我能够使用以下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:

1 个答案:

答案 0 :(得分:1)

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