影像的原理
http://www.lizibuluo.com/8bit/
這個網站就是一個隨意的繪圖的網站,可以看到很多小方塊,這些小方塊就是像素,
像素是指由影像的小方格組成的,這些小方塊都有一個明確的位置和被分配的色彩數值,小方格顏色和位置就決定該影像所呈現出來的樣子,
可以將像素視為整個影像中不可分割的單位或者是元素,不可分割的意思是它不能夠再切割成更小單位抑或是元素,它是以一個單一顏色的小格存在 ,每一個點陣影像包含了一定量的像素,這些像素決定影像在螢屏上所呈現的大小,
影像的另一個組成元素就是—解析度,解析度決定了位圖影像細節的精細程度,
通常情況下,影像的解析度越高,所包含的像素就越多,影像就越清晰,印刷的質量也就越好,同時,它也會增加檔案占用的存盤空間,常見的解析度就有1980x1080等,
像素值的存取
存取的基本思路就是把一張圖片,或者一些像素值,轉化成一個二維陣列,一般用的顏色就是R G B,新建一個陣列,這個陣列中的每個點,就是一個顏色的元素,然后再把陣列中的每個點畫出來即可,
上代碼
說了這么多我們先上代碼,先寫一個界面,繼承JFrame,`
public class ImagePad extends JFrame {
public ImagePad(){
setTitle ("像素畫");
setSize (1800,800);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[] args) {
new ImagePad ();// 顯示界面
}
然后我們需要重寫 JFrame 本身的繪制方法 paint,
public void paint (Graphics g){
super.paint(g);
//亂數
Random random = new Random();
random.nextInt(256); // 從0開始數256個 【0,256)
//隨機一個陣列的像素值
int [][] colorArr = new int[500][500];
//遍歷
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
int red = random.nextInt (256);
int green = random.nextInt (256);
int blue = random.nextInt (256);
int value = ((255 & 0xFF) << 24) |
((red & 0xFF) << 16) |
((green & 0xFF) << 8) |
((blue & 0xFF) << 0);
colorArr[i][j]= value;
}
}
// 繪制原始圖形
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
Color color1 = new Color (colorArr[i][j]);
g.setColor (color1);
g.fillRect (100+i,100+j,1,1);
}
}
這樣我們就繪制了一個隨機顏色的像素畫,

前面講到,一張圖片,可以轉化為二維陣列,我們處理陣列里面的元素,就可以處理圖片了,比如我們可以做上面這張圖片的馬賽克處理,
//馬賽克
for (int i = 0; i < 500; i+=20) {
for (int j = 0; j < 500; j+=20) {
int value = colorArr[i][j];
int red = (value>>16)&0xFF;
int green = (value>>8)&0xFF;
int blue = (value>>0)&0xFF;
int gray = (red+green+blue)/3;
Color color1 = new Color (red,green,blue);
g.setColor (color1);
g.fillRect (610+i,100+j,20,20);
}
}
效果如下圖:

以此類推,把RGB值都分別減小,就可以得到灰度處理,
//灰度處理
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
int value = colorArr[i][j];
int red = (value>>16)&0xFF;
int green = (value>>8)&0xFF;
int blue = (value>>0)&0xFF;
int gray = (red+green+blue)/3;
Color color2 = new Color(gray,gray,gray);
g.setColor(color2);
g.fillRect(1120+i,100+j, 1, 1);
}
}
效果如下:

這樣我們就對影像處理有了初步的理解,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/302878.html
標籤:其他
