Android培訓班(29)

來源:互聯網
上載者:User

<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->

接著來分析帶抖動轉換的565演算法:

void to_565_raw_dither(int width)

{

unsigned char in[3];

unsigned short out;

int i = 0;

int e;

建立兩個點的誤差儲存數組。

int* error = malloc((width+2) * 3 * sizeof(int));

int* next_error = malloc((width+2) * 3 * sizeof(int));

清空誤差數組。

memset(error, 0, (width+2) * 3 * sizeof(int));

memset(next_error, 0, (width+2) * 3 * sizeof(int));

計算數組是使用三個點誤差來計算,所以從-3開始。

error += 3; // array goes from [-3..((width+1)*3+2)]

next_error += 3;

讀取原檔案裡的資料。

while(read(0, in, 3) == 3) {

計算當前點的值,當然這裡已經使用以前點值進行擴散。

int r = in[0] + error[i*3+0];

int rb = (r < 0) ? 0 : ((r > 255) ? 255 : r);

int g = in[1] + error[i*3+1];

int gb = (g < 0) ? 0 : ((g > 255) ? 255 : g);

int b = in[2] + error[i*3+2];

int bb = (b < 0) ? 0 : ((b > 255) ? 255 : b);

out = to565(rb, gb, bb);

write(1, &out, 2);

計算誤差值,以便下一個點值進行顏色調整。

#define apply_error(ch) {

next_error[(i-1)*3+ch] += e * 3 / 16;

next_error[(i)*3+ch] += e * 5 / 16;

next_error[(i+1)*3+ch] += e * 1 / 16;

error[(i+1)*3+ch] += e - ((e*1/16) + (e*3/16) + (e*5/16));

}

當前計算出來的顏色,與565裡恢複出來的誤差值。

e = r - from565_r(out);

apply_error(0);

e = g - from565_g(out);

apply_error(1);

e = b - from565_b(out);

apply_error(2);

#undef apply_error

++i;

到最後,清空誤差值。

if (i == width) {

// error <- next_error; next_error <- 0

int* temp = error; error = next_error; next_error = temp;

memset(next_error, 0, (width+1) * 3 * sizeof(int));

i = 0;

}

}

刪除分配的空間。

free(error-3);

free(next_error-3);

return;

}

 


到這裡就把這個簡短的程式碼分析完成了,別看這麼一段程式,它其實還是包括很多技術在裡面的,比如shell的瞭解、565顏色編碼、遊程編碼、色差抖動演算法。因此,要寫出上面這個程式,要懂得比較的廣博的知識,誰說知識無用呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.