1 /*
2 * Copyright (C) 2015-2018 Alibaba Group Holding Limited
3 */
4
5 #include <stdio.h>
6 #include "to_rgb565.h"
7 #include <stdbool.h>
8
9 #define RGB565_RED 0xf800
10 #define RGB565_GREEN 0x07e0
11 #define RGB565_BLUE 0x001f
12
13 /* Multiplication over 8 bit emulation */
14 #define mul8(a, b) (((a) * (b) + 128 + (((a) * (b) + 128) >> 8)) >> 8)
15
16 /* Conversion from rgb24 to rgb565 */
17 #define rgb2rgb565(r, g, b) \
18 ((mul8(r, 31) << 11) | (mul8(g, 63) << 5) | (mul8(b, 31) << 0))
19
rgb888torgb565(unsigned char * rgb888_buf,int rgb888_size,unsigned short * rgb565_buf,int rgb565_size)20 int rgb888torgb565(unsigned char *rgb888_buf, int rgb888_size,
21 unsigned short *rgb565_buf, int rgb565_size)
22 {
23 int i = 0;
24 unsigned char Red = 0;
25 unsigned char Green = 0;
26 unsigned char Blue = 0;
27 int count = 0;
28
29 if (rgb888_buf == NULL || rgb888_size <= 0 || rgb565_buf == NULL || \
30 rgb565_size <= 0 || (rgb565_size < (rgb888_size / 3) * 2)) {
31 printf("Invail input parameter in %s\n", __func__);
32 return -1 ;
33 }
34
35 for (i = 0; i < rgb888_size; i += 3) {
36 Red = rgb888_buf[i] >> 3;
37 Green = rgb888_buf[i + 1] >> 2;
38 Blue = rgb888_buf[i + 2] >> 3;
39 rgb565_buf[count++] = ((Red << 11) | (Green << 5) | (Blue));
40 }
41 return count;
42 }
43
rgb565torgb888(unsigned short * rgb565_buf,int rgb565_size,unsigned char * rgb888_buf,int rgb888_size)44 int rgb565torgb888(unsigned short *rgb565_buf, int rgb565_size, unsigned char *rgb888_buf, int rgb888_size)
45 {
46 int i = 0;
47 unsigned char Red = 0;
48 unsigned char Green = 0;
49 unsigned char Blue = 0;
50 int count = 0;
51
52 if (rgb565_buf == NULL || rgb565_size <= 0 || rgb888_buf == NULL || rgb888_size <= 0) {
53 printf("Invaild input parameter in %s\n", __func__);
54 return -1;
55 }
56
57 for (i = 0; i < rgb565_size; i++) {
58 // 获取RGB单色,并填充低位
59 Red = (rgb565_buf[i] & RGB565_RED) >> 8 ;
60 Green = (rgb565_buf[i] & RGB565_GREEN) >> 3 ;
61 Blue = (rgb565_buf[i] & RGB565_BLUE) << 3 ;
62 // 连接
63 rgb888_buf[count++] = Red;
64 rgb888_buf[count++] = Green;
65 rgb888_buf[count++] = Blue;
66 }
67 return count;
68 }
69
70