Nodes/ComfyUI-ZML-Image/ZML_图像Base64互转
ComfyUI Node

ZML_图像Base64互转

Image to Base64 and back — the glue for talking to APIs

By zml-w·Created about a year ago·Updated 2 months ago· 218
ZML_图像Base64互转
  • 图像
  • Base64字符串
  • 图像
Base64字符串

Almost every image API on the internet - vision models, background-removal services, img2img endpoints - wants your picture as a Base64 string, because a JSON payload can't carry raw bytes. This node converts an image to a Base64-encoded PNG string, and does the reverse: paste a Base64 string in, get an image tensor out. Both directions run at once if you feed both inputs, which makes it the natural glue when you're building an API-calling pipeline in the ZML pack's HTTP corner.

How it works

The code is a thin, honest wrapper. Image → Base64: it takes the tensor, converts to a PIL image, encodes it as PNG in memory (BytesIO), and base64-encodes the bytes. Base64 → image: it decodes the string, opens it as a PIL image, and converts back to a normalized tensor. Two practical details worth knowing:

  • It encodes as PNG. That matters because PNG is lossless - an API that expects a JPEG-style compression level or a specific bit depth may choke, but you'll never lose quality in the round trip.
  • It operates on the first image of the batch (squeeze(0)). Feed it a 4-image batch and you get one image's Base64; if you need per-item encoding, do it one at a time.

The inputs

Both are optional - you can use the node in one direction only:

  • 图像 - the image to encode.
  • Base64字符串 - the string to decode.

Outputs: Base64字符串 (STRING) and 图像 (IMAGE). In practice you use the output you need and ignore the other; if a direction is unfed, its output is None (or an empty string / 1×1 tensor on failure).

Installing

Standard pack:

cd ComfyUI/custom_nodes
git clone https://github.com/zml-w/ComfyUI-ZML-Image

restart, or ComfyUI Manager. Uses Pillow and torch, both already in the pack's requirements and in any ComfyUI install. Translation patch at https://github.com/zml-w/ZZZ_ZML_English_Patch.

Common issues

Three things bite people. First, size: a Base64 PNG of a big image is huge - a 1MP photo can be over a megabyte of text, which is slow to paste into a widget and slow to send in a request body. Downscale before encoding if the API allows it. Second, the single-image behavior: batches quietly collapse to one image, so if you expected 5 Base64 strings from a 5-image batch, you got one. Third, the error handling is silent - a malformed Base64 string or a non-image returns a placeholder (empty string, or a 1×1 tensor) rather than an error, so a "successful" run can hide a decode failure. If you're feeding the output to an HTTP request, wire the 响应文本 status code somewhere visible and sanity-check before you blame the endpoint.

Categoryimage/ZML_图像/图像

Inputs (2)

NameTypeDefaultDescription
图像optIMAGE
Base64字符串optSTRING

Outputs (2)

NameTypeDescription
Base64字符串STRING
图像IMAGE