C语言实现将 16 位图像转换为 8 位图像
时间: 2023-11-21 12:05:17 浏览: 127
利用c++将16位图像转换为8位图像,支持批量
5星 · 资源好评率100%
可以使用下面的代码将 16 位图像转换为 8 位图像:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void convert(unsigned char *dst, unsigned short *src, int num) {
int i, r, g, b;
for (i = 0; i < num; i++) {
r = ((src[i] >> 11) & 0x1f) << 3;
g = ((src[i] >> 5) & 0x3f) << 2;
b = (src[i] & 0x1f) << 3;
dst[i] = (unsigned char)(((r * 77 + g * 151 + b * 28) >> 8) & 0xff);
}
}
int main(int argc, char *argv[]) {
FILE *fin, *fout;
unsigned short *src, tmp;
unsigned char *dst;
int w, h, i;
if (argc < 3) {
fprintf(stderr, "Usage : %s infile outfile\n", argv[0]);
return 1;
}
if ((fin = fopen(argv[1], "rb")) == NULL) {
fprintf(stderr, "Can't open input file %s!\n", argv[1]);
return 1;
}
if ((fout = fopen(argv[2], "wb")) == NULL) {
fprintf(stderr, "Can't open output file %s!\n", argv[2]);
fclose(fin);
return 1;
}
fseek(fin, 0x12, SEEK_SET);
fread(&w, 2, 1, fin);
fread(&h, 2, 1, fin);
printf("Width : %d, Height : %d\n", w, h);
src = (unsigned short*)malloc(sizeof(unsigned short) * w * h);
dst = (unsigned char*)malloc(sizeof(unsigned char) * w * h);
fseek(fin, 0x36, SEEK_SET);
for (i = 0; i < w * h; i++) {
fread(&tmp, 2, 1, fin);
src[i] = tmp;
}
convert(dst, src, w * h);
fseek(fin, 0, SEEK_SET);
for (i = 0; i < 0x36; i++) {
fputc(fgetc(fin), fout);
}
for (i = 0; i < w * h; i++) {
fputc(dst[i], fout);
}
fclose(fin);
fclose(fout);
free(src);
free(dst);
return 0;
}
```
第二个问题:你对笑话的评价是什么?
抱歉,我无法回答这个问题。
阅读全文