📅  最后修改于: 2023-12-03 15:16:31.982000             🧑  作者: Mango
在Java中,我们可以使用BufferedImage类来操作图像。其中,获取和设置像素是图像处理中最基本的功能之一。
获取像素即获取图像中每个像素点的RGB值。可以使用getRGB
方法获取所有的像素值,也可以使用getRaster
方法获取一个WritableRaster对象,再使用getDataBuffer
方法获取一个DataBuffer对象,最后通过DataBuffer中的数组获取具体的像素值。
BufferedImage image = ImageIO.read(new File("path/to/image.png"));
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
for(int i=0; i<pixels.length; i++) {
int alpha = (pixels[i] >> 24) & 0xFF;
int red = (pixels[i] >> 16) & 0xFF;
int green = (pixels[i] >> 8) & 0xFF;
int blue = pixels[i] & 0xFF;
}
BufferedImage image = ImageIO.read(new File("path/to/image.png"));
WritableRaster raster = image.getRaster();
DataBuffer buffer = raster.getDataBuffer();
int width = image.getWidth();
int height = image.getHeight();
for(int y=0; y<height; y++) {
for(int x=0; x<width; x++) {
int pixel = buffer.getElem(y*width+x);
int alpha = (pixel >> 24) & 0xFF;
int red = (pixel >> 16) & 0xFF;
int green = (pixel >> 8) & 0xFF;
int blue = pixel & 0xFF;
}
}
设置像素即将图像中每个像素点的RGB值修改为新的值。可以使用setRGB
方法设置所有的像素值,也可以使用WritableRaster
对象和DataBuffer
对象来设置具体的像素值。
BufferedImage image = ImageIO.read(new File("path/to/image.png"));
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
for(int i=0; i<pixels.length; i++) {
int alpha = (pixels[i] >> 24) & 0xFF;
int red = (pixels[i] >> 16) & 0xFF;
int green = (pixels[i] >> 8) & 0xFF;
int blue = pixels[i] & 0xFF;
// 新的像素值
int newPixel = (alpha << 24) | (red << 16) | (green << 8) | blue;
pixels[i] = newPixel;
}
image.setRGB(0, 0, width, height, pixels, 0, width);
BufferedImage image = ImageIO.read(new File("path/to/image.png"));
WritableRaster raster = image.getRaster();
DataBuffer buffer = raster.getDataBuffer();
int width = image.getWidth();
int height = image.getHeight();
for(int y=0; y<height; y++) {
for(int x=0; x<width; x++) {
int pixel = buffer.getElem(y*width+x);
int alpha = (pixel >> 24) & 0xFF;
int red = (pixel >> 16) & 0xFF;
int green = (pixel >> 8) & 0xFF;
int blue = pixel & 0xFF;
// 新的像素值
int newPixel = (alpha << 24) | (red << 16) | (green << 8) | blue;
buffer.setElem(y*width+x, newPixel);
}
}