RGB888 转 RGB565

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

FILE* in  ;
FILE* out ;

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

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

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


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,"F:\\CG\\jljt\\bmp\\jljt_320x240_%.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);
        // RGB 888 转 RGB 565(从左到右,从下到上)
        unsigned long line = 239 , col = 0 ;
        for(unsigned long i=0 ,j=0;i<320*240*3;i+=3 ,j++)
        {
            unsigned short color565 = RGB888toRGB565(srcBMP[i+2],srcBMP[i+1],srcBMP[i]);
            dstBMP[line][col++] = color565;
            if(col >= 320)
            {
                col = 0 ;
                line-- ;
            }
        }

        //输出到文件
        out = fopen("C:\\Users\\Administrator\\Desktop\\jljt.img","ab+");
        if(! out)
        {
            printf("open file error...\r\n");
            return 1;
        }
        fwrite(dstBMP,2,320*240,out);
        fflush(out);
        fclose(out);
    }

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

}

 

posted @ 2016-11-14 23:08  郭志凯  阅读(4805)  评论(0编辑  收藏  举报