某天,观赏美丽的夕阳,看着满天的红霞铺满海面,偶得灵感,写下了优雅简洁的黑白图片缩放代码,贴出来与诸君共赏。
BOOL hbmp_stretch_bbp1(HBITMAP hbmp_dst, HBITMAP hbmp_src)
{
BOOL ret = FALSE;
BITMAP info_src, info_dst;
GetObject(hbmp_src, sizeof(BITMAP), &info_src);
GetObject(hbmp_dst, sizeof(BITMAP), &info_dst);
if (info_dst.bmBits && info_src.bmBits) {
uint8_t* src = (uint8_t*)info_src.bmBits;
uint8_t* dst = (uint8_t*)info_dst.bmBits;
int pix_src, line_src, line_dst;
uint8_t val;
for (int y = 0; y < info_dst.bmHeight; y++) {
line_src = (y * info_src.bmHeight / info_dst.bmHeight) *
info_src.bmWidthBytes;
line_dst = y * info_dst.bmWidthBytes;
for (int x = 0; x < info_dst.bmWidth; x++) {
pix_src = x * info_src.bmWidth / info_dst.bmWidth;
val = get_bit(&src[line_src], pix_src);
set_bit(&dst[line_dst], x, val);
}
}
ret = TRUE;
}
return ret;
}
set_bit()与get_bit()函数是神来之笔,无需for循环可以直接访问、存贮一行像素的任意位,尽显优雅。
void set_bit(uint8_t *data, int bits, uint32_t val)
{
int bytes = bits / 8;
int offset = bits % 8;
uint32_t op = 0x80 >> offset;
if (val) {
data[bytes] |= op;
}else {
data[bytes] &= (~op);
}
}
uint8_t get_bit(uint8_t* data, int bits)
{
int bytes = bits / 8;
int offset = bits % 8;
uint32_t op = 0x80 >> offset;
return (data[bytes] & op);
}
注:代码在windows MFC环境测试通过,稍作修改,可以移植到其它平台。