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

Python如何使用Wand库绘制并保存2位单色BMP格式图像

解决方案

你需要调整属性设置顺序,增加颜色量化步骤,同时在保存时指定BMP的位深度导出参数,修改后的代码如下:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color
draw=Drawing()

### SET VARS
mystepvalue = 15

with Image(filename='empty.bmp') as image:
    print(image.size)
    image.antialias = False
    draw.stroke_width = 1
    draw.stroke_color = Color('black')
    draw.fill_color = Color('black')
    
    # --- draw the lines ---
    for xpos in range(0,4790,mystepvalue):
        draw.line( (xpos,0), (xpos, image.height) )

    draw(image)

    # 以下为修改后的导出配置
    # 1. 先切换到灰度色彩空间
    image.colorspace = "gray"
    # 2. 量化到2种颜色,关闭抖动避免出现中间灰度
    image.quantize(number_colors=2, colorspace_type='gray', dither=False)
    # 3. 设置位深度为1(对应2色单色BMP,若需要2位4色就改为2)
    image.depth = 1
    image.antialias = False
    # 4. 保存时指定BMP导出格式参数,bmp1对应1位单色,bmp2对应2位4色
    image.save(filename='result.bmp', define={'bmp:format': 'bmp1'})

原代码问题说明

  1. 属性设置顺序错误:色彩空间切换需要在深度设置、颜色量化之前执行
  2. 缺少颜色量化步骤:绘制后的图像可能存在中间灰度值,即使手动设置了深度,ImageMagick默认保存BMP时会自动匹配能覆盖所有颜色的位深度,导致输出为24位
  3. 未指定BMP专属导出参数:Wand默认导出BMP时会优先使用兼容性最高的24位格式,哪怕图像内部深度已经调整完成。

如果需要导出2位(4色)BMP,只需把image.depth = 1改为image.depth = 2,同时把define={'bmp:format': 'bmp1'}改为define={'bmp:format': 'bmp2'}即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:09:04