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

使用Pillow的Image.frombytes(mode='1')生成白色图片失败,求问题定位

Fixing Image.frombytes(mode='1') When Creating White Pillow Images

Oh, I’ve stumbled over this exact issue with Pillow’s 1-bit mode before—it’s full of little counterintuitive details that trip up even experienced users. Let’s walk through the most likely mistakes you’re making and how to fix them.

Why Your White Image Isn’t Turning Out Right

1. You’ve Got the Color Bit Mapping Backwards

The biggest gotcha here: In Pillow’s mode='1' (1-bit binary images), 0 represents white, and 1 represents black. If you were generating byte data filled with 0xFF (all bits set to 1), you’re actually making a fully black image, not white. That’s the most common mistake with this mode.

2. You’re Miscalculating the Required Byte Count

1-bit mode packs 8 pixels into a single byte, and every row of pixels is padded to the nearest 8-bit boundary. So if your image width isn’t a multiple of 8, you can’t just divide width by 8—you need to round up. For example:

  • A 100px wide image needs (100 + 7) // 8 = 13 bytes per row (not 12, which would only cover 96 pixels). Skip this padding, and your image will have distorted, misaligned pixels.

Working Code to Generate a White 1-bit Image

Here’s a tested snippet that creates a clean white image with mode='1':

from PIL import Image

# Set your desired image size
width = 100
height = 50

# Calculate bytes needed per row (pad to 8-bit boundary)
bytes_per_row = (width + 7) // 8
# Create all-zero byte data (each 0 bit = white pixel)
byte_data = b'\x00' * bytes_per_row * height

# Generate the image
white_image = Image.frombytes('1', (width, height), byte_data)

# Quick verification: check the top-left pixel (should be 0 for white)
print(f"Top-left pixel value: {white_image.getpixel((0, 0))}")
# Save or display the image
white_image.save('white_1bit.png')

Quick Checks to Debug Further

  • Use getpixel() to confirm pixel values—if you see 1 where you expect white, you’re using the wrong byte values.
  • If your image looks stretched or has weird artifacts, recheck the bytes_per_row calculation—padding errors are the usual suspect here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:21:25