昨天晚上做一个java分析图片RGB值的案例的时候,copy了网上的代码,在运行代码后出现如下问题:
检查了半天,也转译了路径,发现都是不行,这个文件读取不到,今天早上又在网上查了下,试了半天,最后使用加载器解决:
package com.pic;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class PictureResolve {
/**
* 读取一张图片的RGB值
* @throws Exception
*/
public void getImagePixel(String image) throws Exception {
//先获取路径的URL
URL imageResource = this.getClass().getResource(image);
int[] rgb = new int[3];
//根据URL获取路径,生成file对象
File file = new File(imageResource.getPath());
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
System.out.println("width=" + width + ",height=" + height + ".");
System.out.println("minx=" + minx + ",miniy=" + miny + ".");
// Map<String, Integer> RGBMap = new HashMap<>();
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
System.out.println("i=" + i + ",j=" + j + ":(" + rgb[0] + ","
+ rgb[1] + "," + rgb[2] + ")");
}
}
}
/**
* 返回屏幕色彩值
*
* @param x
* @param y
* @return
* @throws AWTException
*/
public int getScreenPixel(int x, int y) throws AWTException { // 函数返回值为颜色的RGB值。
Robot rb = null; // java.awt.image包中的类,可以用来抓取屏幕,即截屏。
rb = new Robot();
Toolkit tk = Toolkit.getDefaultToolkit(); // 获取缺省工具包
Dimension di = tk.getScreenSize(); // 屏幕尺寸规格
System.out.println(di.width);
System.out.println(di.height);
Rectangle rec = new Rectangle(0, 0, di.width, di.height);
BufferedImage bi = rb.createScreenCapture(rec);
int pixelColor = bi.getRGB(x, y);
return 16777216 + pixelColor; // pixelColor的值为负,经过实践得出:加上颜色最大值就是实际颜色值。
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
int x = 0;
PictureResolve pr = new PictureResolve();
x = pr.getScreenPixel(100, 345);
System.out.println(x + " - ");
pr.getImagePixel("aaa.jpg");
}
}
同过加载器,完美解决URL imageResource = this.getClass().getResource(image);