Java DIP - 图像像素
图像包含一个二维像素数组。它实际上是构成图像的那些像素的值。通常,图像可以是彩色或灰度的。
在 Java 中,BufferedImage 类用于处理图像。您需要调用 BufferedImage 类的 getRGB() 方法来获取像素的值。
获取像素值
可以使用以下语法接收像素值−
Color c = new Color(image.getRGB(j, i));
获取 RGB 值
方法 getRGB() 将行和列索引作为参数并返回相应的像素。对于彩色图像,它返回三个值(红色、绿色、蓝色)。它们可以通过以下方式获取−
c.getRed(); c.getGreen(); c.getBlue();
获取图像的宽度和高度
可以通过调用BufferedImage类的getWidth()和getHeight()方法来获取图像的高度和宽度。其语法如下−
int width = image.getWidth(); int height = image.getHeight();
除了这些方法之外,BufferedImage类还支持其他方法。它们被简要描述−
Sr.No. | 方法 &描述 |
---|---|
1 |
copyData(WritableRaster outRaster) 计算 BufferedImage 的任意矩形区域并将其复制到指定的 WritableRaster 中。 |
2 |
getColorModel() 返回图像的 ColorModel。 |
3 |
getData() 将图像作为一个大图块返回。 |
4 |
getData(Rectangle rect) 它计算并返回 BufferedImage 的任意区域。 |
5 |
getGraphics() 此方法返回 Graphics2D,但在此用于向后兼容。 |
6 |
getHeight() 它返回 BufferedImage 的高度。 |
7 |
getMinX() 它返回此 BufferedImage 的最小 x 坐标。 |
8 |
getMinY() 它返回此 BufferedImage 的最小 y 坐标。 |
9 |
getRGB(int x, int y) 它返回默认 RGB 颜色模型 (TYPE_INT_ARGB) 和默认 sRGB 颜色空间中的整数像素。 |
10 |
getType() 它返回图像类型。 |
示例
以下示例演示了如何使用 java BufferedImage 类来显示大小为 (100 x 100) 的图像的像素 −
import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.JFrame; class Pixel { BufferedImage image; int width; int height; public Pixel() { try { File input = new File("blackandwhite.jpg"); image = ImageIO.read(input); width = image.getWidth(); height = image.getHeight(); int count = 0; for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { count++; Color c = new Color(image.getRGB(j, i)); System.out.println("S.No: " + count + " Red: " + c.getRed() +" Green: " + c.getGreen() + " Blue: " + c.getBlue()); } } } catch (Exception e) {} } static public void main(String args[]) throws Exception { Pixel obj = new Pixel(); } }
输出
执行上述示例时,它将打印以下图像的像素 −
原始图像

像素输出
如果向下滚动输出,将看到以下模式−