public static void main(String[] args) throws IOException {
//原图
String inString = "f:/abc.jpg";
//灰度
String outString = "f:/abc_gray.jpg";
Rgb2Gray.toGray(inString, outString);
Rgb2Gray.testRead(inString);
}
// 读取图片信息
@Test
public final static void testRead(String inString) {
File file = new File(inString);
FileChannel fc = null;
if (file.exists() && file.isFile()) {
try {
FileInputStream fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
Rgb2Gray.writeDown(width, height);
}
// 将图片信息写入到文件中
@Test
public final static void writeDown(int width, int height) {
String src = "f:\\test\\ss\\ss.txt";
File file = new File(src);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(file);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = sdf.format(date);
bw.write("时间:" + now + "\n");
bw.write("宽:" + width + "px" + "\n");
bw.write("高:" + height + "px" + "\n");
pw.flush();
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
// 测试写入内容
try {
BufferedReader bReader = new BufferedReader(new FileReader(file));
String line = bReader.readLine();
while ((line = bReader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 灰度图片
@Test
public final static void toGray(String str1, String str2)
throws IOException {
BufferedImage src = ImageIO.read(new File(str1));
System.out.println();
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = op.filter(src, null);
ImageIO.write(src, "JPEG", new File(str2));
}