img* bmp_read(FILE* fptr) { img* dat; try { dat = new img; } catch (bad_alloc& err) { img_err("*bmp", "OOM"); return NULL; } s_fread((char*) &bfType, sizeof(Word), 1, fptr); s_fread((char*) &bfSize, sizeof(DWord), 1, fptr); s_fread((char*) &bfReserved1, sizeof(Word), 1, fptr); s_fread((char*) &bfReserved2, sizeof(Word), 1, fptr); s_fread((char*) &bfOffBits, sizeof(DWord), 1 , fptr); s_fread((char*) &biSize, sizeof(DWord), 1, fptr); s_fread((char*) &biWidth, sizeof(DWord), 1, fptr); s_fread((char*) &biHeight, sizeof(DWord), 1, fptr); s_fread((char*) &biPlanes, sizeof(Word), 1, fptr); s_fread((char*) &biBitCount, sizeof(Word), 1, fptr); s_fread((char*) &biCompression, sizeof(DWord), 1, fptr); s_fread((char*) &biSizeImage, sizeof(DWord), 1, fptr); s_fread((char*) &biXPelsPerMeter, sizeof(DWord), 1, fptr); s_fread((char*) &biYPelsPerMeter, sizeof(DWord), 1, fptr); s_fread((char*) &biClrUsed, sizeof(DWord), 1, fptr); s_fread((char*) &biClrImportant, sizeof(DWord), 1, fptr); if (biCompression >= 1 || biWidth != 512 || biHeight != 512 || (biBitCount != 8 && biBitCount != 24)) { img_err("~*.bmp", "Unsupported BMP Binary."); } if (biBitCount < 16) { for (ushort n=0; n < 256; ++n) { s_fread((char*) &temp, 4, 1, fptr); } } for (int j=511; j > -1; --j) { if (biBitCount == 8) { s_fread((char*) Buffer, 1, 512, fptr); for (ushort i=0; i < 512; ++i) { dat->pix[j][i] = Buffer[i]; // dat.hist[ Buffer[i] ] += 1; } } else if (biBitCount == 24) { s_fread((char*) Buffer24, 1, (512 * 24) / 8, fptr); for (ushort i=0; i < 512; ++i) { memcpy((char*) &temp, Buffer24 + 3 * i, 3); dat->pix[j][i] = temp.r; // dat.hist[ dat.pix[j][i] ] += 1; } } } fclose(fptr); return dat; }
img* read_img(const char* fp) { FILE* fptr = fopen(fp, "rb"); if (fptr == NULL) { img_err(fp, "File does not exist."); } return imr(fptr); }
bool write_img(img* dat, const char* fp) { FILE* fptr = fopen(fp, "wb"); if (fptr == NULL) { img_err(fp, "Cannot write to file."); } return imw(dat, fptr); }
void s_fread(char* arptr, size_t size, ushort elems, FILE* fptr) { if (fread(arptr, size, elems, fptr) != (size * elems)) { if (ferror(fptr) == 0) { return; } cout << strerror(ferror(fptr)) << endl; perror("bad permissions/corrupted file read"); img_err("*", "should be a valid perror above"); } }