1

虽然我想将一些图像和白色画布与 GD 合并,但以下程序使合并后的图像成为灰度。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gd.h>

int main(int argc, char *argv[])
{
    gdImagePtr src, dst, canvas;
    FILE *fp, *out;

    fp = fopen("./image.jpg", "r");
    out = fopen("./image_.jpg", "w");

    src = gdImageCreateFromJpeg(fp);

    dst = gdImageCreate(150, 94);

    gdImageCopyResampled(dst, src, 0, 0, 0, 0, 150, 94, 150, 94);

    canvas = gdImageCreate(150, 94);
    int ccolor = gdImageColorAllocateAlpha(canvas, 255, 255, 255, 255);
    gdImageFilledRectangle(canvas, 0, 0, 150, 94, ccolor);
    gdImageCopy(canvas, dst, 0, 0, 0, 0, 150, 94);
    dst = canvas;
    gdImageJpeg(dst, out, 95);

    return 0;
}

图像.jpg

在此处输入图像描述

图像_.jpg

在此处输入图像描述

相比之下,以下带有 ImageMagick 的程序会生成非灰度图像。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wand/MagickWand.h>

int main(int argc, char *argv[])
{
    MagickWand *wand;
    MagickWand *canvas_wand;
    PixelWand  *canvas_color;

    MagickWandGenesis();

    wand         = NewMagickWand();
    canvas_wand  = NewMagickWand();
    canvas_color = NewPixelWand();

    MagickReadImage(wand, "./image.jpg");

    PixelSetRed(canvas_color,   255);
    PixelSetGreen(canvas_color, 255);
    PixelSetBlue(canvas_color,  255);
    PixelSetAlpha(canvas_color, 255);
    MagickNewImage(canvas_wand, 150, 94, canvas_color);
    MagickCompositeImage(canvas_wand, wand, AtopCompositeOp, 0, 0);
    DestroyMagickWand(wand);
    wand = canvas_wand;

    MagickWriteImage(wand, "./image_.jpg");

    DestroyPixelWand(canvas_color);
    DestroyMagickWand(wand);
    MagickWandTerminus();

    return 0;
}

有没有一种好方法可以通过GD合并制作非灰度图像?

供参考

$ gdlib-config --version
2.0.36
$
4

1 回答 1

1

您需要通过调用该gdImageCreateTrueColor方法来初始化/分配“非灰度”图像。gdImageCreate根本不足以满足您的需求。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gd.h>

int main(int argc, char *argv[])
{
    gdImagePtr src, dst, canvas;
    FILE *fp, *out;

    fp = fopen("./image.jpg", "r");
    out = fopen("./image_.jpg", "w");

    src = gdImageCreateFromJpeg(fp);

    // dst = gdImageCreate(150, 94);
    dst = gdImageCreateTrueColor(150, 94);

    gdImageCopyResampled(dst, src, 0, 0, 0, 0, 150, 94, 150, 94);

    // canvas = gdImageCreate(150, 94);
    canvas = gdImageCreateTrueColor(150, 94);
    int ccolor = gdImageColorAllocateAlpha(canvas, 255, 255, 255, 255);
    gdImageFilledRectangle(canvas, 0, 0, 150, 94, ccolor);
    gdImageCopy(canvas, dst, 0, 0, 0, 0, 150, 94);
    dst = canvas;
    gdImageJpeg(dst, out, 95);

    return 0;
}
于 2013-07-21T02:30:20.740 回答