Last active
March 1, 2021 18:03
-
-
Save brummer10/b150c3b6e09ca1abba2a27d05e1ff9c9 to your computer and use it in GitHub Desktop.
convert and scale png files to svg files with cairo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cairo.h> | |
#include <cairo-svg.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <libgen.h> | |
// gcc -g png2svg.c -lm `pkg-config --cflags --libs cairo` -o png2svg | |
void strdecode(char *target, const char *needle, const char *replacement) { | |
char buffer[1024] = { 0 }; | |
char *insert_point = &buffer[0]; | |
const char *tmp = target; | |
size_t needle_len = strlen(needle); | |
size_t repl_len = strlen(replacement); | |
while (1) { | |
const char *p = strstr(tmp, needle); | |
if (p == NULL) { | |
strcpy(insert_point, tmp); | |
break; | |
} | |
memcpy(insert_point, tmp, p - tmp); | |
insert_point += p - tmp; | |
memcpy(insert_point, replacement, repl_len); | |
insert_point += repl_len; | |
tmp = p + needle_len; | |
} | |
strcpy(target, buffer); | |
} | |
int main(int argc, char* argv[]) { | |
if (argc < 1) { | |
fprintf(stdout, "usage: %s name.png scalefactor\n", basename(argv[0])); | |
return 1; | |
} | |
cairo_surface_t *getpng = cairo_image_surface_create_from_png (argv[1]); | |
int width = cairo_image_surface_get_width(getpng); | |
int height = cairo_image_surface_get_height(getpng); | |
double sx = 1.0; | |
if (argc > 2) { | |
sx = atof(argv[2]); | |
} | |
char svg_file[80]; | |
sprintf(svg_file, basename(argv[1])); | |
strdecode(svg_file, ".png", ".svg"); | |
fprintf(stderr, "%s\n",svg_file); | |
cairo_surface_t *frame = cairo_svg_surface_create(svg_file, width*sx, height*sx); | |
cairo_t *crf = cairo_create(frame); | |
cairo_scale(crf, sx, sx); | |
cairo_set_source_surface(crf, getpng, 0, 0); | |
cairo_paint(crf); | |
cairo_surface_flush(frame); | |
cairo_destroy(crf); | |
cairo_surface_destroy(getpng); | |
cairo_surface_destroy(frame); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment