비압축 포맷인 BMP(Bitmap) 파일을 효율적인 JPEG 포맷으로 변환하는 과정은 임베디드 시스템이나 이미지 처리 어플리케이션에서 자주 사용되는 기술입니다. 이 과정의 핵심은 BMP 파일의 헤더를 해석하여 픽셀 데이터를 추출하고, libjpeg 라이브러리를 통해 손실 압축을 수행하는 것입니다.
1. BMP 파일 구조 정의
BMP 파일은 바이너리 데이터가 정렬 없이 저장되므로, 구조체 선언 시 바이트 정렬을 해제하는 #pragma pack(1) 지시어가 필요합니다. BMP 파일은 파일 정보를 담은 헤더와 이미지의 세부 메타데이터를 담은 인포 헤더로 구성됩니다.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "jpeglib.h"
#pragma pack(push, 1)
// BMP 파일 헤더 (14바이트)
typedef struct {
uint16_t type; // "BM" 식별자
uint32_t size; // 전체 파일 크기
uint16_t reserved1;
uint16_t reserved2;
uint32_t offset; // 실제 픽셀 데이터 시작 위치
} BMPFileHeader;
// BMP 정보 헤더 (40바이트)
typedef struct {
uint32_t header_size; // 헤더 크기
int32_t width; // 이미지 가로 너비
int32_t height; // 이미지 세로 높이
uint16_t planes; // 컬러 플레인 (항상 1)
uint16_t bit_depth; // 픽셀당 비트 수 (예: 24bit)
uint32_t compression; // 압축 방식
uint32_t image_size; // 이미지 데이터 크기
int32_t x_resolution; // 가로 해상도
int32_t y_resolution; // 세로 해상도
uint32_t colors_used; // 사용된 색상 수
uint32_t colors_important; // 중요한 색상 수
} BMPInfoHeader;
#pragma pack(pop)
2. BMP 데이터를 JPEG로 변환하는 핵심 로직
BMP 파일은 일반적으로 하단에서 상단 방향(Bottom-up)으로 픽셀 데이터가 저장되며, 색상 순서 또한 RGB가 아닌 BGR 순서로 기록됩니다. 따라서 JPEG로 압축하기 전, 데이터의 수직 반전과 색상 채널 교환 과정이 선행되어야 합니다.
/**
* BMP 파일을 읽어 JPEG 파일로 압축 생성
* @param src_bmp 원본 BMP 파일 경로
* @param dest_jpg 생성할 JPEG 파일 경로
* @param quality 압축 품질 (1-100)
*/
int convert_bmp_to_jpeg(const char *src_bmp, const char *dest_jpg, int quality) {
FILE *fp_src = fopen(src_bmp, "rb");
if (!fp_src) {
perror("Source file open failed");
return -1;
}
BMPFileHeader file_hdr;
BMPInfoHeader info_hdr;
// 헤더 정보 읽기
fread(&file_hdr, sizeof(BMPFileHeader), 1, fp_src);
fread(&info_hdr, sizeof(BMPInfoHeader), 1, fp_src);
int width = info_hdr.width;
int height = (info_hdr.height < 0) ? -info_hdr.height : info_hdr.height;
int channels = info_hdr.bit_depth / 8;
// 픽셀 데이터 로드 (24비트 기준)
long data_size = (long)width * height * channels;
unsigned char *raw_data = (unsigned char *)malloc(data_size);
fseek(fp_src, file_hdr.offset, SEEK_SET);
fread(raw_data, 1, data_size, fp_src);
fclose(fp_src);
// BGR -> RGB 변환 및 상하 반전 처리
unsigned char *processed_buffer = (unsigned char *)malloc(data_size);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int src_idx = ((height - 1 - y) * width + x) * channels;
int dest_idx = (y * width + x) * channels;
processed_buffer[dest_idx + 0] = raw_data[src_idx + 2]; // Red
processed_buffer[dest_idx + 1] = raw_data[src_idx + 1]; // Green
processed_buffer[dest_idx + 2] = raw_data[src_idx + 0]; // Blue
}
}
// libjpeg 초기화 및 압축 설정
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *fp_dest = fopen(dest_jpg, "wb");
if (!fp_dest) {
free(raw_data);
free(processed_buffer);
return -1;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp_dest);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress(&cinfo, TRUE);
// 스캔라인 단위로 데이터 작성
JSAMPROW row_pointer[1];
int row_stride = width * 3;
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = &processed_buffer[cinfo.next_scanline * row_stride];
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
fclose(fp_dest);
jpeg_destroy_compress(&cinfo);
free(raw_data);
free(processed_buffer);
return 0;
}
3. 메인 함수 실행 예시
아래 코드는 작성된 변환 함수를 호출하여 실제 이미지를 처리하는 예시입니다. 품질 파라미터를 조절하여 파일 크기와 화질 사이의 균형을 맞출 수 있습니다.
int main(void) {
const char *input_file = "sample.bmp";
const char *output_file = "compressed.jpg";
int compression_quality = 90;
if (convert_bmp_to_jpeg(input_file, output_file, compression_quality) == 0) {
printf("성공: %s 파일이 생성되었습니다.\n", output_file);
} else {
printf("오류: 이미지 변환에 실패했습니다.\n");
}
return 0;
}