I found libafterimage to be incredibly simple to use.
In this snippet I also scale the image to at most width
or at most height
, while preserving aspect:
#include <libAfterImage/afterimage.h>
int convert_image_to_jpeg_of_size(const char* infile, const char* outfile, const double max_width, const double max_height)
{
ASImage* im;
ASVisual* asv;
ASImage* scaled_im;
double height;
double width;
double pixelzoom;
double proportion;
im = file2ASImage(infile, 0xFFFFFFFF, SCREEN_GAMMA, 0, ".", NULL);
if (!im) {
return 1;
}
proportion = (double)im->width / (double)im->height;
asv = create_asvisual(NULL, 0, 0, NULL);
if (proportion > 1) {
/* Oblong. */
width = max_width;
pixelzoom = max_width / im->width;
height = (double)im->height * pixelzoom;
} else {
height = max_height;
pixelzoom = max_height / im->height;
width = (double)im->width * pixelzoom;
}
scaled_im = scale_asimage(asv, im, width, height, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT);
/* writing result into the file */
ASImage2file(scaled_im, NULL, outfile, ASIT_Jpeg, NULL);
destroy_asimage(&scaled_im);
destroy_asimage(&im);
return 0;
}