我试图用一些 C 代码创建一个 .pam 图像,但 fwrite 函数只将对应的 ASCII 码写入文件,而不是十六进制值。
文件的头部需要是 ASCII,实际的图像数据需要只是 rgb 和 alpha 的十六进制值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *out;
out = fopen("C:/Users/entin/Desktop/write.pam", "wb+");
if (out == NULL) {
printf("Unable to access file.\n");
} else {
//everything concerning the head
//buffer the head to not get an overflow
unsigned char headbuf[100];
sprintf(headbuf, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");
//reduce head to nessesary length so it dosent output useless NULL's
int len = strlen(headbuf);
unsigned char head[len];
sprintf(head, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");
//write head to file
fwrite(head, sizeof (head), 1, out);
//initiating pixel values
unsigned char buf[8];
int r = 0; //AA
int g = 0; //BB
int b = 0; //CC
int a = 255; //DD
//for now just change the red and green values
for (r = 0; r <= 255; r++) {
for (g = 0; g <= 255; g++) {
//coppy pixel data to buffer
sprintf(buf, "%02X%02X%02X%02X", r, g, b, a);
//write buffer to head
fwrite(buf, sizeof (buf), 1, out);
}
}
}
fclose(out);
printf("fin");
getchar();
return (EXIT_SUCCESS);
}
它输出我想要的头部,但像素值也写在它们的 ASCII 值中
它输出 ENDHDR\nAABBCCDD
作为。45 4E 44 48 44 52 0A 41 41 42 42 43 43 44 44
它应该像这样输出:45 4E 44 48 44 52 0A AA BB CC DD
我修正了我的代码,只是将值写成对应的 ASCII 码。
这里是固定代码
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *out;
out = fopen("C:/Users/entin/Desktop/write.pam", "wb+");
if (out == NULL) {
printf("Unable to access file.\n");
} else {
//head
fprintf(out, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");
//initiating pixel values
int r = 0; //red
int g = 0; //green
int b = 255; //blue
int a = 255; //alpha
//for now just change the red and green values
for (r = 0; r <= 255; r++) {
for (g = 0; g <= 255; g++) {
//call the numbers as theirr ASCII counterpart and print them
fprintf(out, "%c%c%c%c", r, g, b, a);
}
}
}
fclose(out);
printf("fin");
getchar();
return (EXIT_SUCCESS);
}
这是第一个结果
我是一名优秀的程序员,十分优秀!