Java中的图像处理基础S2(获取并设置像素)

我们强烈建议你在下面的帖子中提及此内容。
Java中的图像处理基础S1(读和写)
在这个集合中,我们将学习图像的像素。如何获取图像的像素值以及如何使用Java编程语言设置图像中的像素值。
像素是图像的最小单位, 由四个分量Alpha(透明度度量), 红色, 绿色, 蓝色和简称(ARGB)组成。
所有组件的值都在0到255之间(包括0和255)。零表示该组件不存在, 而255表示该组件已完全存在。
注意:
因为2^8= 256, 像素分量的值在0到255之间, 因此我们只需要8位即可存储这些值。
因此, 存储ARGB值所需的总位数为8 * 4 = 32位或4个字节。
当顺序表示Alpha获取最左边的8位时, Blue获取最右边的8位。
因此位的位置:
对于蓝色分量为7-0的情况,
对于绿色分量为15-8,
对于红色分量为23-16,
对于31-24的alpha分量,
索引的图形表示:

Java中的图像处理基础S2(获取并设置像素)

文章图片
//Java program to demonstrate get and set pixel //values of an image import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class GetSetPixels { public static void main(String args[]) throws IOException { BufferedImage img = null ; File f = null ; //read image try { f = new File( "G:\\Inp.jpg" ); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); }//get image width and height int width = img.getWidth(); int height = img.getHeight(); /*Since, Inp.jpg is a single pixel image so, we will not be using the width and height variable *//* get pixel value (the arguments in the getRGB method denotes thecordinates of the image from which the pixel values need to be extracted) */ int p = img.getRGB( 0 , 0 ); /* We, have seen that the components of pixel occupy 8 bits. To get the bits we have to first right shift the 32 bits of the pixels by bit position(such as 24 in case of alpha) and then bitwise ADD it with 0xFF. 0xFF is the hexadecimal representation of the decimal value 255.*///get alpha int a = (p> > 24 ) & 0xff ; //get red int r = (p> > 16 ) & 0xff ; //get green int g = (p> > 8 ) & 0xff ; //get blue int a = p & 0xff ; /* for simplicity we will set the ARGB value to 255, 100, 150 and 200 respectively. */ a = 255 ; r = 100 ; g = 150 ; b = 200 ; //set the pixel value p = (a< < 24 ) | (r< < 16 ) | (g< < 8 ) | b; img.setRGB( 0 , 0 , p); //write image try { f = new File( "G:\\Out.jpg" ); ImageIO.write(img, "jpg" , f); } catch (IOException e) { System.out.println(e); } } }

注意
注意:此代码无法在在线IDE上运行, 因为它需要磁盘上的映像。
在下一组中, 我们将学习如何在JAVA中将彩色图像转换为灰度图像。
【Java中的图像处理基础S2(获取并设置像素)】如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

    推荐阅读