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

如何将任意图片转换为hex triplet数组 适配Scratch绘图需求

实现核心逻辑

所有方案的通用流程都是一致的:

  • 读取目标图片,统一转换为RGB色彩模式(过滤透明通道)
  • 按需将图片缩放/裁剪到你需要的尺寸,避免后续Scratch绘制耗时过长
  • 逐行逐像素读取对应RGB三个通道的色值
  • 将每个通道的0-255数值转换为两位十六进制字符串,拼接为#RRGGBB格式的hex triplet
  • 按像素排列顺序将色值存入数组即可

Python实现(依赖Pillow库)

先安装依赖:
pip install pillow

代码示例:

from PIL import Image

def img_to_hex_triplet(img_path, target_size=None):
    img = Image.open(img_path).convert("RGB")
    if target_size:
        img = img.resize(target_size)
    width, height = img.size
    hex_arr = []
    for y in range(height):
        row = []
        for x in range(width):
            r, g, b = img.getpixel((x, y))
            hex_color = f"#{r:02x}{g:02x}{b:02x}"
            row.append(hex_color)
        hex_arr.append(row)
    return hex_arr

# 调用示例:将图片缩为32*32尺寸后转换
result = img_to_hex_triplet("你的本地图片路径.png", target_size=(32, 32))
print(result)

JavaScript实现(基于Canvas,前端可用)

代码示例:

function imgToHexTriplet(imgElement, targetWidth, targetHeight) {
    const canvas = document.createElement('canvas');
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(imgElement, 0, 0, targetWidth, targetHeight);
    const hexArr = [];
    for (let y = 0; y < targetHeight; y++) {
        const row = [];
        for (let x = 0; x < targetWidth; x++) {
            const pixel = ctx.getImageData(x, y, 1, 1).data;
            const r = pixel[0].toString(16).padStart(2, '0');
            const g = pixel[1].toString(16).padStart(2, '0');
            const b = pixel[2].toString(16).padStart(2, '0');
            row.push(`#${r}${g}${b}`);
        }
        hexArr.push(row);
    }
    return hexArr;
}

Java实现(依赖ImageIO)

代码示例:

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImgToHexConverter {
    public static List<List<String>> imgToHexTriplet(String imgPath, int targetWidth, int targetHeight) throws IOException {
        File imgFile = new File(imgPath);
        BufferedImage originalImg = ImageIO.read(imgFile);
        BufferedImage resizedImg = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        resizedImg.getGraphics().drawImage(originalImg, 0, 0, targetWidth, targetHeight, null);
        
        List<List<String>> hexArr = new ArrayList<>();
        for (int y = 0; y < targetHeight; y++) {
            List<String> row = new ArrayList<>();
            for (int x = 0; x < targetWidth; x++) {
                int rgb = resizedImg.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                String hexColor = String.format("#%02x%02x%02x", r, g, b);
                row.add(hexColor);
            }
            hexArr.add(row);
        }
        return hexArr;
    }

    public static void main(String[] args) throws IOException {
        List<List<String>> result = imgToHexTriplet("你的本地图片路径.png", 32, 32);
        System.out.println(result);
    }
}

Scratch适配注意事项

如果生成的数组是给Scratch画笔功能使用,建议提前把图片缩放到64*64以下尺寸,不然逐像素绘制的耗时会非常长。如果原图带有透明区域,可以提前把透明部分填充为你需要的背景色,避免转换出的色值不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:54:03