1

Though I want to to conflate some image and white canvas with GD, Following program makes the conflated image grayscale.

#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;
}

image.jpg

enter image description here

image_.jpg

enter image description here

By contrast, the following program with ImageMagick makes a non-grayscale image.

#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;
}

Is there a good way to make non-grayscale image with conflation by GD?

FYI

$ gdlib-config --version
2.0.36
$
cubicdaiya
  • 368
  • 1
  • 6

1 Answers1

1

You'll need to initialize/allocate a "non-grayscale" image by calling the gdImageCreateTrueColor method. gdImageCreate is simply is not enough to meet your needs.

#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;
}
emcconville
  • 23,800
  • 4
  • 50
  • 66