如何使用 ImageMagick 将 PNG 格式转换为 BGR 565 格式

How to convert a PNG to BGR 565 format using ImageMagick

我正在尝试使用 Image Magick 将 PNG 文件转换为 BGR 565 位图图像。我已经进行了大量研究,但无法得出答案。谁能帮帮我?

编译此 C 程序并将其安装在您的搜索路径中 "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);
        }
    }

然后运行

magick file.png -depth 8 rgb:- | rgbtobgr565 > file.bgr565

为了完整起见,这里是将 bgr565 像素转换回 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);
    }
}