首页 > 代码库 > RGB888 转 RGB565

RGB888 转 RGB565

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE* in  ;
FILE* out ;

unsigned char srcBMP[320 * 240 * 3] = {0};
unsigned char dstBMP[320 * 240 * 2] = {0};

char inFileName[500]  = {0}; //待转换的图片的文件名
char outFileName[500] = {0}; //输出文件名

const unsigned long bmpStart = 1 ;  //起始图片序号
const unsigned long bmpEnd = 5257 ;  //结束图片序号


unsigned short RGB888toRGB565(unsigned char red, unsigned char green, unsigned char blue)
{
        unsigned short B = (blue >> 3) & 0x001F;
        unsigned short G = ((green >> 2) << 5) & 0x07E0;
        unsigned short R = ((red >> 3) << 11) & 0xF800;

        return (unsigned short) (R | G | B);
}

int main()
{
    for(unsigned long index = bmpStart ; index <=bmpEnd ;index++ )
    {
        // 合成文件名
        sprintf(inFileName,"C:\\Users\\Administrator\\Desktop\\CG\\badBMP\\BAD_%.4ld.bmp",index);
        printf("convert bmp : %s...\r\n",inFileName);
        // 读取RGB888内容
        in = fopen(inFileName,"rb+");
        if(! in)
        {
            printf("open file error...\r\n");
            return 1;
        }
        fseek(in,54,SEEK_SET);
        fread(srcBMP,1,320*240*3,in);
        fclose(in);
        // 转换
        for(unsigned long i=0 ,j=0;i<320*240*3;i+=3 ,j+=2)
        {
            unsigned short color565 = RGB888toRGB565(srcBMP[i],srcBMP[i+1],srcBMP[i+2]);
            memcpy(dstBMP+j,&color565,2);
        }
        //输出到文件
        out = fopen("C:\\Users\\Administrator\\Desktop\\CG\\bad.img","ab+");
        if(! out)
        {
            printf("open file error...\r\n");
            return 1;
        }
        fwrite(dstBMP,1,320*240*2,out);
        fflush(out);
        fclose(out);
    }

    printf("complete...\r\n");
    getchar();

}

 

RGB888 转 RGB565