gpt4 book ai didi

java - 在java中读/写图像

转载 作者:行者123 更新时间:2023-12-01 15:12:55 26 4
gpt4 key购买 nike

我想使用java来读取/写入图像,并且我有一些代码。但我不知道如何使用这些代码,尤其是在参数 String...

实际上在这些代码附带的示例demo中,用法是这样的:

double[] data = Image.load("src/chap08_romsrams/common/lena256.ppm", "../common/lena256.ppm");

还有这个:

Image.write(l, "P3", 256, "src/chap08_romsrams/ex1_roms/lena_processed.ppm", "lena_processed.ppm");

假设我有一个名为 lena.ppm 的 256*256 图像,它与 java 文件位于同一文件夹中,我如何使用这些函数来读取/写入图像...?

非常感谢!

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Image {
public static double[] load(String... fn) {
InputStream in = null;

for (String string : fn) {
try {
in = new FileInputStream(string);
} catch (IOException e) {
/* Empty */
}
if (in != null) break;
}

if (in == null) {
throw new RuntimeException("Failed to load input image in Image.load(String...), tried to load image from " + fn);
}

BufferedReader reader = new BufferedReader( new InputStreamReader(in) );

try {
String type = reader.readLine(); // Type
reader.readLine(); // Comment
String res = reader.readLine(); // Dimensions
reader.readLine(); // Intensity range

Pattern p = Pattern.compile("(\\d+) (\\d+)");
Matcher m = p.matcher(res);
m.matches();
Integer width = Integer.parseInt(m.group(1));
Integer height = Integer.parseInt(m.group(2));

System.err.println(width + "x" + height);

double[] data = new double[width * height * ((type.equals("P3")) ? 3 : 1)];
String line;
int i = 0;
while((line = reader.readLine()) != null)
data[i++] = Integer.parseInt(line);

reader.close();

return data;

} catch(IOException e) {
throw new RuntimeException(e);
}
}

public static void write(List<Double> data, String... fn) {
write(data, "P2", 1024, fn);
}

public static void write(List<Double> data, String type, int width, String... fn) {
OutputStream out = null;

for (String string : fn) {
try {
out = new FileOutputStream(string);
} catch (IOException e) {
/* Empty */
}
if (out != null) break;
}

if (out == null) {
throw new RuntimeException("Failed to file for output in Image.write(List<Double>, String, int, String...), tried to open " + fn);
}

PrintStream ps = new PrintStream(out);

ps.println(type);
int height = data.size() / (width * ((type.equals("P3") ? 3 : 1))); //1024;
ps.println("#generated");
ps.println("" + width + " " + height);
ps.println("255");
for(Double d : data)
ps.println((int)(d.doubleValue()));
}

}

最佳答案

你为什么不试试Java Imaging API 。这是example如何进行图像 IO。希望这有帮助..

关于java - 在java中读/写图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com