Java 图片读取:ImageIO 和 OpenCV 方法详解
使用 Java 读取图片可以使用 Java 内置的 ImageIO 类或者第三方库如 OpenCV。
使用 ImageIO 读取图片的步骤如下:
- 使用 ImageIO 的静态方法 read() 读取图片文件,返回一个 BufferedImage 对象。
File file = new File('image.jpg');
BufferedImage image = ImageIO.read(file);
- 可以通过 BufferedImage 对象的 getWidth() 和 getHeight() 方法获取图片宽度和高度。
int width = image.getWidth();
int height = image.getHeight();
- 如果需要对图片进行操作,可以通过 BufferedImage 对象的 getRGB() 和 setRGB() 方法获取和设置像素点的颜色值。
int pixel = image.getRGB(x, y);
// 获取 RGB 值
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = pixel & 0xff;
// 设置 RGB 值
int newPixel = (red << 16) | (green << 8) | blue;
image.setRGB(x, y, newPixel);
使用 OpenCV 读取图片的步骤如下:
- 导入 OpenCV 库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
- 使用 Imgcodecs 的静态方法 imread() 读取图片文件,返回一个 Mat 对象。
Mat mat = Imgcodecs.imread('image.jpg');
- 可以通过 Mat 对象的 width() 和 height() 方法获取图片宽度和高度。
int width = mat.width();
int height = mat.height();
- 如果需要对图片进行操作,可以通过 Mat 对象的 get() 和 put() 方法获取和设置像素点的颜色值。
double[] pixel = mat.get(x, y);
// 获取 BGR 值
double blue = pixel[0];
double green = pixel[1];
double red = pixel[2];
// 设置 BGR 值
double[] newPixel = {blue, green, red};
mat.put(x, y, newPixel);
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nVMy 著作权归作者所有。请勿转载和采集!