1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
#include "bmpRw.h" #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h>
typedef struct __attribute__((packed)) BITMAPFILEHEADER { uint16_t bfType; uint32_t bfSize; uint16_t bfReserved1; uint16_t bfReserved2; uint32_t bfOffBits; }BITMAPFILEHEADER; typedef struct __attribute__((packed)) BITMAPINFOHEADER { uint32_t biSize; uint32_t biWidth; uint32_t biHeight; uint16_t biPlanes; uint16_t biBitCount; uint32_t biCompression; uint32_t biSizeImage; uint32_t biXPelsPerMeter; uint32_t biYPelsPerMeter; uint32_t biClrUsed; uint32_t biClrImportant; }BITMAPINFOHEADER;
const BITMAPFILEHEADER dstHead = { .bfType = 19778, .bfSize = 766136, .bfReserved1 = 0, .bfReserved2 = 0, .bfOffBits = 54};
const BITMAPINFOHEADER dstInfo = { .biSize = 40, .biWidth = 639, .biHeight = 399, .biPlanes = 1, .biBitCount = 24, .biCompression = 0, .biSizeImage = 766082, .biXPelsPerMeter = 3779, .biYPelsPerMeter = 3779, .biClrUsed = 0, .biClrImportant = 0};
int readBmp(char *fileName, void *pData) { if(!fileName || !pData){ return -1; } int i; BITMAPFILEHEADER head; BITMAPINFOHEADER info; size_t nElemSize; size_t nPaddingSize;
FILE *fp = fopen(fileName, "rb"); if (fp == NULL){ return -1; }
fread(&head, sizeof(BITMAPFILEHEADER), 1, fp); fread(&info, sizeof(BITMAPINFOHEADER), 1, fp);
nElemSize = info.biBitCount / 8; nPaddingSize = ((info.biWidth * nElemSize + 3) & (size_t)-4) - info.biWidth * nElemSize;
fseek(fp, head.bfOffBits, SEEK_SET); for (i = info.biHeight - 1; i >= 0; --i){ fread(pData + i * info.biWidth * nElemSize, nElemSize, info.biWidth, fp); fseek(fp, nPaddingSize, SEEK_CUR); }
fclose(fp); return 0; }
int writeBmp(char *fileName, void *pData) { if (!fileName || !pData) { return -1; }
int i; size_t nElemSize; size_t nPaddingSize; FILE *fp = fopen(fileName, "wb"); if (fp == NULL) { return -1; }
fwrite(&dstHead, 1, sizeof(BITMAPFILEHEADER), fp); fwrite(&dstInfo, 1, sizeof(BITMAPINFOHEADER), fp);
nElemSize = dstInfo.biBitCount / 8; nPaddingSize = ((dstInfo.biWidth * nElemSize + 3) & (size_t)-4) - dstInfo.biWidth * nElemSize; uint8_t *pPadding = (uint8_t *)malloc(sizeof(uint8_t) * nPaddingSize); if(!pPadding) return -1; memset(pPadding, 0, sizeof(uint8_t) * nPaddingSize);
for (i = dstInfo.biHeight - 1; i >= 0; --i) { fwrite(pData + i * dstInfo.biWidth * nElemSize, nElemSize, dstInfo.biWidth, fp); fwrite(pPadding, 1, nPaddingSize, fp); }
fclose(fp);
free(pPadding); pPadding = NULL;
return 0; }
|