# How to convert RGBA pixel to RGB565

Hi everyone
Im working on image converter using python to convert .png to rgb565 using transparency(yes i know, that exist online and work great, but i need automate a whole process)
The code convert each pixel and save the result in a .bin, that work fine with not at all, and i cant figure out what i missing or how lvgl image converter work.

my code is

``````R=pix[w,h]
G=pix[w,h]
B=pix[w,h]

R=R>>3
G=G>>2
B=B>>3

G_low = G & 0x07
G_high = G >> 3

# For 16-bit color depth:
# Byte 0: Green 3 lower bit, Blue 5 bit
# Byte 1: Red 5 bit, Green 3 higher bit
# Byte 2: Alpha byte (only with LV_IMG_CF_TRUE_COLOR_ALPHA)

rgb = (G_low<<13) | (B<<8) | (R<<3) | G_high
``````

for example, if the pixel is (255,0,0), the output is 0x00f8
(0,255,0), the output is 0xE007
(0,0,255), the output is 0x1f00

that is the same as output lvgl converter, but if i set pixel like this(231,48,64)
, my output is 0x88E1 and the lvgl converter is 0x88E9.
In other image lvgl generate 0xE0E3, and my code generate 0xD802
I don’t expect them to see my code and tell me the bug, but I feel like I’m missing something important and maybe someone can know
,because all of topic i can read, my method is correct, but iit s your converter
that work,so:
how its conversion works?
Thanks!

FYI, the newer image converter is written in Node.js and should be straightforward to automate with a bash script.

The conversion logic for RGB565 is here; it’s JavaScript but it should be readable for this purpose. I am not 100% sure if you are shifting the bits exactly the same way. `c16` is effectively a 16-bit int.

Thanks for your help, im ended using the old PHP script, for thar i use this lines in python:

``````        cmd="php img_conv_core.php \"name=outputFolderPath/"+image_name[i]+"&img="+"inputFolderPath/"+image_name[i]+".png&format=bin_565&cf=true_color_alpha\""

proc = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
result = proc.stdout.read()                             #for wait the conversion end

``````

I dont know why my original script dont work, the shift convertion bits its OK, i suspect the reading pixel values its the problem, i hope the code above will help.

Regards