Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีตั้งค่าพิกเซล (RGB) ของภาพด้วย Java

พิกเซลเก็บค่า ARGB ในหน่วยความจำ 32-bit (8-bit ต่อช่อง) วิธีแก้ไขสีภาพ:

  1. วนลูปทุกพิกเซลในภาพ
  2. ดึงค่าพิกเซลด้วย getRGB()
  3. แยกค่า ARGB
  4. ปรับค่า RGB ตามต้องการ
  5. สร้างพิกเซลใหม่และตั้งค่าด้วย setRGB()

วิธี 1: ใช้ Color Class

import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class SetPixels {
    public static void main(String args[]) throws IOException {
        File file = new File("D:\\Images\\cat.jpg");
        BufferedImage img = ImageIO.read(file);
        
        for (int y = 0; y < img.getHeight(); y++) {
            for (int x = 0; x < img.getWidth(); x++) {
                int pixel = img.getRGB(x, y);
                Color c = new Color(pixel, true);
                
                int r = c.getRed();
                int g = c.getGreen();
                int b = c.getBlue();
                
                // ปรับสี: ทำให้เขียวและน้ำเงิน = 150
                g = 150;
                b = 150;
                
                img.setRGB(x, y, new Color(r, g, b).getRGB());
            }
        }
        
        ImageIO.write(img, "jpg", new File("D:\\Images\\modified.jpg"));
        System.out.println("Done...");
    }
}

วิธี 2: ใช้ Bit Shifting

// แยกค่า ARGB
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;

// รวมค่าใหม่
p = (a << 24) | (r << 16) | (g << 8) | b;
img.setRGB(x, y, p);

ภาพอินพุตและเอาต์พุต

ภาพจะเปลี่ยนสีตามการปรับค่า RGB ที่เขียนในโค้ด