我试图用一些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
p.45 TH 48小时52 0A 41 41 42 42 h hh hh
它应该像这样输出: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);
}
这是第一个结果