RGB888 转 RGB565

Posted 郭志凯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

RGB888 到 RGB565 / 位移

一文了解各平台RGB565和RGB888区别

RGB888与RGB565互相转换原理

RGB888转换为RGB565格式

使用 SSE2 优化 RGB565 到 RGB888 的转换

android rgb888和argb565有啥区别