I'm trying to use Image Magick to convert a PNG file into a BGR 565 bitmap image. I've done a fair amount of research and haven't been able to come up with an answer. Can anyone help me out?
Compile this C program and install it in your search path as "rgbtobgr565"
/* rgbtobgr565 - convert 24-bit RGB pixels to 16-bit BGR565 pixels
Written in 2016 by Glenn Randers-Pehrson <glennrp@users.sf.net>
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>.
Use with ImageMagick or GraphicsMagick to convert 24-bit RGB pixels
to 16-bit BGR565 pixels, e.g.,
magick file.png -depth 8 rgb:- | rgbtobgr565 > file.bgr565
Note that the 16-bit pixels are written in network byte order (most
significant byte first), with blue in the most significant bits and
red in the least significant bits.
ChangLog:
Jan 2017: changed bgr565 from int to unsigned short (suggested by
Steven Valsesia)
*/
#include <stdio.h>
int main()
{
int red,green,blue;
unsigned short bgr565;
while (1) {
red=getchar(); if (red == EOF) return (0);
green=getchar(); if (green == EOF) return (1);
blue=getchar(); if (blue == EOF) return (1);
bgr565 = (unsigned short)(red * 31.0 / 255.0) |
(unsigned short)(green * 63.0 / 255.0) << 5 |
(unsigned short)(blue * 31.0 / 255.0) << 11;
putchar((bgr565 >> 8) & 0xFF);
putchar(bgr565 & 0xFF);
}
}
Then run
magick file.png -depth 8 rgb:- | rgbtobgr565 > file.bgr565
For completeness, here is the program for converting bgr565 pixels back to rgb:
/* bgr565torgb - convert 16-bit BGR565 pixels to 24-bit RGB pixels
Written in 2016 by Glenn Randers-Pehrson <glennrp@users.sf.net>
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>.
Use with ImageMagick or GraphicsMagick to convert 16-bit BGR565 pixels
to 24-bit RGB pixels, e.g.,
bgr565torgb < file.bgr565 > file.rgb
magick -size WxH -depth 8 file.rgb file.png
*/
#include <stdio.h>
int main()
{
int rgbhi,rgblo,red,green,blue;
while (1) {
rgbhi=getchar(); if (rgbhi == EOF) return (0);
rgblo=getchar(); if (rgblo == EOF) return (1);
putchar((rgblo & 0x1F) << 3 | (rgblo & 0x14) >> 3 );
putchar((rgbhi & 0x07) << 5 |
(rgblo & 0xE0) >> 3 |
(rgbhi & 0x06) >> 1);
putchar((rgbhi & 0xE0) | (rgbhi >> 5) & 0x07);
}
}