如何在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
相关产品推荐
相关产品推荐

