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

如何在Java中为P6格式PPM图像编码RGB值?

问题描述

我正尝试用P6编码生成PPM图像文件,最开始使用如下代码创建文件:

private static void writeImage(String image, String outputPath) {
    try (PrintWriter out = new PrintWriter(outputPath + "output.pbm")) {
        out.println(image);
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}

目前我已经完成了文件头部的构建逻辑,但经过多次尝试和资料检索,始终搞不清楚怎么把每个像素的RGB值转换成可以添加到文件中、能被正确识别的内容。

我的具体问题是:
如何将一组RGB值(例如(red=255, blue=192, green=0))转换为P6格式PPM图像可正确识别的对应内容?


解决方案

感谢Solomon Slow的评论提供了思路,以下是整理后的完整实现方案:
现在改用如下函数创建并输出文件:

private static void writeImage(String header, List<Byte> image, String filepath) {
    try (FileOutputStream out = new FileOutputStream(filepath)) {
        out.write(header.getBytes(StandardCharsets.UTF_8));
        for(byte b:image) {
            out.write(b);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
        throw new TerminateProgram();
    }
}

传入的头部参数在其他函数中定义如下:

String header = "P6" + "\n" +
                width + " " +
                height + "\n" +
                "255" + "\n";

最后使用ArrayList构建字节值列表,按如下方式添加每个像素的数值:

List<Byte> image = new ArrayList<>();

// red, green, blue 已经提前定义为0-255区间的int值
image.add((byte)(red));
image.add((byte)(green));
image.add((byte)(blue));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:36:03