Android培训班(29)

来源:互联网 发布:外国人 知乎 编辑:程序博客网 时间:2024/05/01 03:35

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

接着来分析带抖动转换的565算法:

 

voidto_565_raw_dither(int width)

{

unsignedchar in[3];

unsignedshort out;

inti = 0;

inte;

 

创建两个点的误差保存数组。

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) {

 

计算当前点的值,当然这里已经使用以前点值进行扩散。

intr = in[0] + error[i*3+0];

intrb = (r < 0) ? 0 : ((r > 255) ? 255 : r);

 

intg = in[1] + error[i*3+1];

intgb = (g < 0) ? 0 : ((g > 255) ? 255 : g);

 

intb = in[2] + error[i*3+2];

intbb = (b < 0) ? 0 : ((b > 255) ? 255 : b);

 

out= to565(rb, gb, bb);

write(1,&out, 2);

 

 

计算误差值,以便下一个点值进行颜色调整。

#defineapply_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);

 

#undefapply_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颜色编码、游程编码、色差抖动算法。因此,要写出上面这个程序,要懂得比较的广博的知识,谁说知识无用呢?