我正在尝试使用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());
}
}现在,我所需要做的就是构建以P6格式表示图像的文本。构建标题很容易,但尽管进行了实验和搜索,但我似乎不知道如何将每个像素的RGB值转换为可以添加到文件中的字符串。
我的问题是:
我如何获取一个RGB值(例如(red=255, blue=192, green=0))并获得一个将在P6格式的图像中正确识别的字符串表示?
解决方案:给所罗门·斯洛的评论,因为他帮助我解决了这个问题。这是我为那些想要细节的人想出的解决方案。我现在使用这个函数来创建和输出文件:
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 already defined as ints from 0 to 255
image.add((byte)(red));
image.add((byte)(green));
image.add((byte)(blue));发布于 2021-11-01 15:26:44
来自,http://netpbm.sourceforge.net/doc/ppm.html
每个像素都是一个红色、绿色和蓝色样本的三重奏,按顺序排列。每个示例以纯二进制形式以1或2字节表示。最重要的字节是第一个。
这意味着ppm文件不是文本文件。您可能应该使用FileOutputStream而不是PrintWriter。
这有点棘手,因为Java的byte数据类型是签名的。您需要将红色、绿色和蓝色级别的int值设置在0.255范围内,然后将其转换为byte。也许可以看到java unsigned byte to stream
至于文件的文本头,我将使用的方法是对标题进行build a String表示,然后调用header.getBytes()将其转换为可以写入FileOutputStream的byte数组。
https://stackoverflow.com/questions/69798978
复制相似问题