Skip to content

Instantly share code, notes, and snippets.

@jcupitt
Last active February 29, 2020 12:06
Show Gist options
  • Save jcupitt/039ecdc172712cbb8969 to your computer and use it in GitHub Desktop.
Save jcupitt/039ecdc172712cbb8969 to your computer and use it in GitHub Desktop.
watermark an image with the vips8 C API
/* watermark an image with libvips C. It handles monon, RGB and CMYK images.
*
* compile with
gcc -g -Wall watermark.c `pkg-config vips --cflags --libs`
*/
#include <vips/vips.h>
int
main( int argc, char **argv )
{
/* The colour we paint the text with. We need different colours for
* monoo, RGB and CMYK.
*/
double colour_mono[1] = { 1.0 };
double colour_rgb[3] = { 1.0, 0.0, 0.0 };
double colour_cmyk[4] = { 0.0, 1.0, 0.0, 0.5 };
double zeros[4] = { 0.0, };
VipsImage *base;
VipsImage **t;
VipsImage *in;
const double *colour;
int overlay_bands;
VipsImage *overlay;
if( VIPS_INIT( argv[0] ) )
vips_error_exit( NULL );
if( argc != 4 )
vips_error_exit( "usage: %s in-file out-file \"message\"",
argv[0] );
base = vips_image_new();
t = (VipsImage **) vips_object_local_array( VIPS_OBJECT( base ), 12 );
if( !(t[0] = vips_image_new_from_file( argv[1],
"access", VIPS_ACCESS_SEQUENTIAL,
NULL )) ) {
g_object_unref( base );
vips_error_exit( NULL );
}
in = t[0];
/* Make the mask. We pick a text colour that matches the image type.
*/
switch( in->Type ) {
case VIPS_INTERPRETATION_B_W:
colour = colour_mono;
overlay_bands = 1;
break;
case VIPS_INTERPRETATION_sRGB:
colour = colour_rgb;
overlay_bands = 3;
break;
case VIPS_INTERPRETATION_CMYK:
colour = colour_cmyk;
overlay_bands = 4;
break;
default:
vips_error_exit( "unsupported image interpretation" );
}
if( vips_text( &t[1], argv[3],
"width", 500,
"dpi", 300,
NULL ) ||
vips_linear( t[1], &t[2],
colour, zeros, overlay_bands, NULL ) ||
vips_linear1( t[1], &t[3], 0.3, 0, NULL ) ||
vips_bandjoin2( t[2], t[3], &t[4], NULL ) ||
vips_cast( t[4], &t[5], VIPS_FORMAT_UCHAR, NULL ) ||
vips_copy( t[5], &t[6],
"interpretation", in->Type,
NULL ) ||
vips_embed( t[6], &t[7], 100, 100,
t[6]->Xsize + 200, t[6]->Ysize + 200, NULL ) ||
vips_replicate( t[7], &t[8],
1 + in->Xsize / t[7]->Xsize,
1 + in->Ysize / t[7]->Ysize, NULL ) ||
vips_crop( t[8], &t[9], 0, 0,
in->Xsize, in->Ysize, NULL ) ) {
g_object_unref( base );
vips_error_exit( NULL );
}
overlay = t[9];
/* Blend the image and overlay and write to output.
*/
if( vips_composite2( in, overlay, &t[10],
VIPS_BLEND_MODE_OVER, NULL ) ||
vips_image_write_to_file( t[10], argv[2], NULL ) ) {
g_object_unref( base );
vips_error_exit( NULL );
}
g_object_unref( base );
return( 0 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment