#include <gd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

gdImagePtr myLoadjpg(char *filename)
{
	FILE *in;
	struct stat stat_buf;
	gdImagePtr im; 
	in = fopen(filename, "rb");
	if (!in) {
		/* Error */
	}   
	if (fstat(fileno(in), &stat_buf) != 0) {
		/* Error */
	}   
	/* Read the entire thing into a buffer
	 *     that we allocate */
	char *buffer = malloc(stat_buf.st_size);
	if (!buffer) {
		/* Error */
	}   
	if (fread(buffer, 1, stat_buf.st_size, in) 
			!= stat_buf.st_size)
	{   
		/* Error */
	}   
	im = gdImageCreateFromPngPtr(
			stat_buf.st_size, buffer);
	/* WE allocated the memory, WE free
	 *     it with our normal free function */
	free(buffer);
	fclose(in);
	return im; 
}

void mySaveJpeg(char *filename,
		gdImagePtr im) 
{
	FILE *out;
	int size;
	char *data;
	out = fopen(filename, "wb");
	if (!out) {
		/* Error */
	}   
	data = (char *) gdImageJpegPtr(im, &size, 75);
	if (!data) {
		/* Error */
	}
	if (fwrite(data, 1, size, out) != size) {
		/* Error */
	}
	if (fclose(out) != 0) {
		/* Error */
	}
	gdFree(data);
}

static gdImagePtr image_new(int w,int h,int colors)
{
	gdImagePtr  img;

	if (colors == 0) {
		img = gdImageCreateTrueColor(w, h);
	} else {
		img = gdImageCreate(w, h);
	}

	return img;
}

int main()
{
	gdImagePtr src,dst;
	src = myLoadjpg("123.jpg");
	dst = image_new(2000, 2000, 0);

	int sx = gdImageSX(src);
	int sy = gdImageSY(src);
	int colors = 0;
	if (colors == 0) {
		gdImageSaveAlpha(dst, 1);
		gdImageAlphaBlending(dst, 0);
	}

	gdImageCopyResampled(dst, src, 0, 0, 0, 0, 2000, 2000, sx, sy);

	if (colors) {
		gdImageTrueColorToPalette(dst, 1, 256);
	}

	mySaveJpeg("456.jpg",dst);
	return 0;
}