📜  Java中的图像处理——获取和设置像素

📅  最后修改于: 2022-05-13 01:54:50.888000             🧑  作者: Mango

Java中的图像处理——获取和设置像素

先决条件 - Java中的图像处理 - 读写

在本集中,我们将了解图像的像素、如何获取图像的像素值以及如何使用Java编程语言设置图像中的像素值。像素是图像的最小单位,由四个分量 Alpha(透明度度量)、红色、绿色、蓝色和简而言之 (ARGB) 组成。所有组件的值都在 0 到 255 之间,包括两个值。零表示组件不存在,255 表示组件完全存在。

因此,存储 ARGB 值所需的总位数为 8*4=32 位或 4 个字节。按照顺序表示,Alpha 获取最左边的 8 位。蓝色获取最右边的 8 位。

因此位位置:

  • 对于蓝色分量为 7-0,
  • 对于绿色分量为 15-8,
  • 对于红色分量 23-16,
  • 对于 31-24 的 alpha 分量,

索引的图形表示:

啊

例子:

Java
// Java program to demonstrate get
// and set pixel values of an image
  
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
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(
                "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png");
            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 the  coordinates 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(
                "C:/Users/hp/Desktop/Image Processing in Java/GFG.png");
            ImageIO.write(img, "png", f);
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}


输出 -