图像在java中的表示_在java中读/写图像

我想用java读/写一个图像,我有一些代码。但我不知道如何使用代码,特别是在参数字符串...

实际上,在与这些代码一起的示例演示中,用法如下所示:

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 data, String... fn) {

write(data, "P2", 1024, fn);

}

public static void write(List 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, 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()));

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值