>>160623Pro-Tipp: ChatGPT kann da bei der Code-Erstellung helfen.
Als kleiner Starter, von ChatGPT generiert:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void identify_png(FILE *f) {
uint8_t header[8];
fread(header, 1, 8, f);
if (memcmp(header, "\x89PNG\r\n\x1a\n", 8)) {
printf("Not a PNG\n");
return;
}
fseek(f, 8, SEEK_SET); // skip signature
uint8_t chunk[25]; // IHDR is 25 bytes including length/type/CRC
fread(chunk, 1, 25, f);
if (memcmp(chunk+4, "IHDR", 4)) {
printf("No IHDR chunk\n");
return;
}
uint32_t width = (chunk[8]<<24)|(chunk[9]<<16)|(chunk[10]<<8)|chunk[11];
uint32_t height = (chunk[12]<<24)|(chunk[13]<<16)|(chunk[14]<<8)|chunk[15];
uint8_t bit_depth = chunk[16];
uint8_t color_type = chunk[17];
printf("PNG %ux%u %u-bit color_type %u\n", width, height, bit_depth, color_type);
}
void identify_jpeg(FILE *f) {
uint8_t buf[2];
fread(buf, 1, 2, f);
if (buf[0] != 0xFF || buf[1] != 0xD8) {
printf("Not a JPEG\n");
return;
}
while (1) {
if (fread(buf, 1, 2, f) != 2) break;
if (buf[0] != 0xFF) continue;
uint8_t marker = buf[1];
if (marker >= 0xC0 && marker <= 0xC3) { // SOF markers
fseek(f, 3, SEEK_CUR);
uint8_t dim[4];
fread(dim, 1, 4, f);
uint16_t height = (dim[0]<<8)|dim[1];
uint16_t width = (dim[2]<<8)|dim[3];
printf("JPEG %ux%u\n", width, height);
return;
} else {
uint8_t size_buf[2];
fread(size_buf,1,2,f);
uint16_t size = (size_buf[0]<<8)|size_buf[1];
fseek(f, size-2, SEEK_CUR);
}
}
printf("JPEG dimensions not found\n");
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s <image>\n", argv[0]);
return 1;
}
FILE *f = fopen(argv[1], "rb");
if (!f) { perror("fopen"); return 1; }
uint8_t sig[8];
fread(sig, 1, 8, f);
fseek(f, 0, SEEK_SET);
if (!memcmp(sig, "\x89PNG\r\n\x1a\n", 8))
identify_png(f);
else if (sig[0]==0xFF && sig[1]==0xD8)
identify_jpeg(f);
else
printf("Unsupported format\n");
fclose(f);
return 0;
}
Getestet, funktioniert - auch wenn es nicht 1:1 das Output von identify ist.