2 ttf2png - True Type Font to PNG converter
3 Copyright (c) 2004-2008 Mikko Rasa
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include FT_FREETYPE_H
45 typedef struct sKerning
67 int convert_numeric_option(char, int);
68 void convert_code_point_range(char, unsigned *, unsigned *);
69 unsigned str_to_code_point(const char *, char **);
70 void convert_size(char, unsigned *, unsigned *);
71 unsigned round_to_pot(unsigned);
72 void *alloc_image_data(size_t, size_t);
73 int init_font(Font *, FT_Face, unsigned, unsigned, bool);
74 int render_grid(Font *, unsigned, unsigned, unsigned, bool);
75 int render_packed(Font *, unsigned, unsigned);
76 int save_defs(const char *, const Font *);
77 int save_png(const char *, const Image *, char);
81 int main(int argc, char **argv)
104 char *out_fn = "font.png";
115 while((i = getopt(argc, argv, "r:s:l:c:o:atvh?ed:pim:n:")) != -1)
120 convert_code_point_range('r', &begin, &end);
123 size = convert_numeric_option('s', 1);
126 cpl = convert_numeric_option('l', 1);
129 convert_size('c', &cellw, &cellh);
160 margin = convert_numeric_option('m', 0);
163 padding = convert_numeric_option('n', 0);
167 if(!strcmp(out_fn, "-"))
178 err = FT_Init_FreeType(&freetype);
181 fprintf(stderr, "Couldn't initialize FreeType library\n");
185 err = FT_New_Face(freetype, fn, 0, &face);
188 fprintf(stderr, "Couldn't load font file\n");
189 if(err==FT_Err_Unknown_File_Format)
190 fprintf(stderr, "Unknown file format\n");
196 const char *name = FT_Get_Postscript_Name(face);
197 printf("Font name: %s\n", name);
198 printf("Glyphs: %ld\n", face->num_glyphs);
201 err = FT_Set_Pixel_Sizes(face, 0, size);
204 fprintf(stderr, "Couldn't set size\n");
209 err = init_font(&font, face, begin, end, autohinter);
215 fprintf(stderr, "No glyphs found in the requested range\n");
220 err = render_packed(&font, margin, padding);
222 err = render_grid(&font, cellw, cellh, cpl, seq);
228 for(i=0; (unsigned)i<font.image.w*font.image.h; ++i)
229 font.image.data[i] = 255-font.image.data[i];
231 err = save_png(out_fn, &font.image, alpha);
236 save_defs(def_fn, &font);
238 for(i=0; (unsigned)i<font.n_glyphs; ++i)
239 free(font.glyphs[i].image.data);
242 free(font.image.data);
245 FT_Done_FreeType(freetype);
252 printf("ttf2png 1.1 - True Type Font to PNG converter\n"
253 "Copyright (c) 2004-2018 Mikko Rasa, Mikkosoft Productions\n"
254 "Distributed under the GNU General Public License\n\n");
256 printf("Usage: ttf2png [options] <TTF file>\n\n");
258 printf("Accepted options (default values in [brackets])\n"
259 " -r Range of code points to convert [0,255]\n"
260 " -s Font size to use, in pixels [10]\n"
261 " -l Number of glyphs to put in one line [auto]\n"
262 " -c Glyph cell size, in pixels (grid mode only) [auto]\n"
263 " -o Output file name (or - for stdout) [font.png]\n");
264 printf(" -a Force autohinter\n"
265 " -t Render glyphs to alpha channel\n"
266 " -i Invert colors of the glyphs\n"
267 " -v Increase the level of verbosity\n"
268 " -e Use cells in sequence, without gaps (grid mode only)\n"
269 " -p Pack the glyphs tightly instead of in a grid\n"
270 " -m Margin around image edges (packed mode only) [0]\n"
271 " -n Padding between glyphs (packed mode only) [1]\n"
272 " -d File name for writing glyph definitions\n"
273 " -h Print this message\n");
276 int convert_numeric_option(char opt, int min_value)
281 value = strtol(optarg, &ptr, 0);
282 if(value<min_value || *ptr)
284 printf("Invalid option argument in -%c %s\n", opt, optarg);
291 void convert_code_point_range(char opt, unsigned *begin, unsigned *end)
296 if(!strcmp(optarg, "all"))
303 value = str_to_code_point(optarg, &ptr);
304 if(value>0 && *ptr==',')
307 value = str_to_code_point(ptr+1, &ptr);
315 printf("Invalid option argument in -%c %s\n", opt, optarg);
319 unsigned str_to_code_point(const char *nptr, char **endptr)
321 if(nptr[0]=='U' && nptr[1]=='+')
322 return strtoul(nptr+2, endptr, 16);
323 else if(nptr[0]&0x80)
330 *endptr = (char *)nptr;
332 for(bytes=1; (bytes<4 && (nptr[0]&(0x80>>bytes))); ++bytes)
333 if((nptr[bytes]&0xC0)!=0x80)
338 code = nptr[0]&(0x3F>>bytes);
339 for(i=1; i<bytes; ++i)
340 code = (code<<6)|(nptr[i]&0x3F);
343 *endptr = (char *)nptr+bytes;
347 else if(isdigit(nptr[0]))
348 return strtoul(nptr, endptr, 0);
352 *endptr = (char *)nptr+1;
357 void convert_size(char opt, unsigned *width, unsigned *height)
362 if(!strcmp(optarg, "auto"))
368 else if(!strcmp(optarg, "autorect"))
375 value = strtol(optarg, &ptr, 0);
381 value = strtol(ptr+1, &ptr, 0);
395 printf("Invalid option argument in -%c %s\n", opt, optarg);
399 unsigned round_to_pot(unsigned n)
411 void *alloc_image_data(size_t a, size_t b)
415 /* Carry out the multiplication manually so we can check for overflow. */
424 fprintf(stderr, "Cannot allocate %lu kbytes of memory for image\n", (unsigned long)(c/1024*b));
431 fprintf(stderr, "Cannot allocate %lu kbytes of memory for image\n", (unsigned long)(a/1024*b));
435 int init_font(Font *font, FT_Face face, unsigned first, unsigned last, bool autohinter)
440 font->ascent = (face->size->metrics.ascender+63)>>6;
441 font->descent = (face->size->metrics.descender+63)>>6;
445 printf("Ascent: %d\n", font->ascent);
446 printf("Descent: %d\n", font->descent);
451 for(i=first; i<=last; ++i)
454 FT_Bitmap *bmp = &face->glyph->bitmap;
459 n = FT_Get_Char_Index(face, i);
464 flags |= FT_LOAD_FORCE_AUTOHINT;
465 FT_Load_Glyph(face, n, flags);
466 FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
469 printf(" Char %u: glyph %u, size %dx%d\n", i, n, bmp->width, bmp->rows);
471 if(bmp->pixel_mode!=FT_PIXEL_MODE_GRAY)
473 fprintf(stderr, "Warning: Glyph %u skipped, not grayscale\n", n);
477 if(font->n_glyphs>=size)
480 font->glyphs = (Glyph *)realloc(font->glyphs, size*sizeof(Glyph));
483 glyph = &font->glyphs[font->n_glyphs++];
486 glyph->image.w = bmp->width;
487 glyph->image.h = bmp->rows;
488 glyph->image.data = (char *)malloc(bmp->width*bmp->rows);
489 if(!glyph->image.data)
491 fprintf(stderr, "Cannot allocate %d bytes of memory for glyph\n", bmp->width*bmp->rows);
494 glyph->offset_x = face->glyph->bitmap_left;
495 glyph->offset_y = face->glyph->bitmap_top-bmp->rows;
496 glyph->advance = (int)(face->glyph->advance.x+32)/64;
498 /* Copy the glyph image since FreeType uses a global buffer, which would
499 be overwritten by the next glyph. Negative pitch means the scanlines
500 start from the bottom. */
503 for(y=0; y<bmp->rows; ++y) for(x=0; x<bmp->width; ++x)
504 glyph->image.data[x+(glyph->image.h-1-y)*glyph->image.w] = bmp->buffer[x-y*bmp->pitch];
508 for(y=0; y<bmp->rows; ++y) for(x=0; x<bmp->width; ++x)
509 glyph->image.data[x+y*glyph->image.w] = bmp->buffer[x+y*bmp->pitch];
514 printf("Loaded %u glyphs\n", font->n_glyphs);
518 font->kerning = NULL;
519 for(i=0; i<font->n_glyphs; ++i) for(j=0; j<font->n_glyphs; ++j)
523 FT_Get_Kerning(face, font->glyphs[i].index, font->glyphs[j].index, FT_KERNING_DEFAULT, &kerning);
525 /* FreeType documentation says that vertical kerning is practically
526 never used, so we ignore it. */
531 if(font->n_kerning>=size)
534 font->kerning = (Kerning *)realloc(font->kerning, size*sizeof(Kerning));
537 kern = &font->kerning[font->n_kerning++];
538 kern->left_code = font->glyphs[i].code;
539 kern->right_code = font->glyphs[j].code;
540 kern->distance = kerning.x/64;
545 printf("Loaded %d kerning pairs\n", font->n_kerning);
550 int render_grid(Font *font, unsigned cellw, unsigned cellh, unsigned cpl, bool seq)
553 int top = 0, bot = 0;
554 unsigned first, last;
555 unsigned maxw = 0, maxh = 0;
557 /* Find extremes of the glyph images. */
558 for(i=0; i<font->n_glyphs; ++i)
562 y = font->glyphs[i].offset_y+font->glyphs[i].image.h;
565 if(font->glyphs[i].offset_y<bot)
566 bot = font->glyphs[i].offset_y;
567 if(font->glyphs[i].image.w>maxw)
568 maxw = font->glyphs[i].image.w;
569 if(font->glyphs[i].image.h>maxh)
570 maxh = font->glyphs[i].image.h;
575 /* Establish a large enough cell to hold all glyphs in the range. */
576 int square = (cellh==cellw);
590 printf("Max size: %u x %u\n", maxw, maxh);
591 printf("Y range: [%d %d]\n", bot, top);
592 printf("Cell size: %u x %u\n", cellw, cellh);
593 if(maxw>cellw || (unsigned)(top-bot)>cellh)
594 fprintf(stderr, "Warning: character size exceeds cell size\n");
599 /* Determine number of characters per line, trying to fit all the glyphs
600 in a square image. */
604 if(cpl>0 && font->n_glyphs/cpl*cellh<=cpl*cellw)
609 first = font->glyphs[0].code;
612 last = font->glyphs[font->n_glyphs-1].code;
614 font->image.w = round_to_pot(cpl*cellw);
616 font->image.h = round_to_pot((font->n_glyphs+cpl-1)/cpl*cellh);
618 font->image.h = round_to_pot((last-first+cpl)/cpl*cellh);
620 font->image.data = (char *)alloc_image_data(font->image.w, font->image.h);
621 if(!font->image.data)
623 memset(font->image.data, 255, font->image.w*font->image.h);
625 for(i=0; i<font->n_glyphs; ++i)
631 glyph = &font->glyphs[i];
636 ci = glyph->code-first;
641 if(cellw>glyph->image.w)
642 cx += (cellw-glyph->image.w)/2;
643 cy += top-glyph->offset_y-glyph->image.h;
648 for(y=0; y<glyph->image.h; ++y) for(x=0; x<glyph->image.w; ++x)
650 if(cx+x>=font->image.w || cy+y>=font->image.h)
652 font->image.data[cx+x+(cy+y)*font->image.w] = 255-glyph->image.data[x+y*glyph->image.w];
659 int render_packed(Font *font, unsigned margin, unsigned padding)
664 unsigned *used_pixels;
665 unsigned cx = margin, cy;
668 /* Compute the total area occupied by glyphs and padding. */
669 for(i=0; i<font->n_glyphs; ++i)
671 size_t a = area+(font->glyphs[i].image.w+padding)*(font->glyphs[i].image.h+padding);
674 fprintf(stderr, "Overflow in counting total glyph area\n");
680 /* Find an image size that's no higher than wide, allowing for some
681 imperfections in the packing. */
682 for(font->image.w=1;; font->image.w<<=1)
684 if(font->image.w<=margin*2)
686 font->image.h = (area*5/4)/(font->image.w-margin*2)+margin*2;
687 if(font->image.h<=font->image.w)
690 font->image.h = round_to_pot(font->image.h);
692 /* Allocate arrays for storing the image and keeping track of used pixels and
693 glyphs. Since glyphs are rectangular and the image is filled starting from
694 the top, it's enough to track the number of used pixels at the top of each
696 font->image.data = (char *)alloc_image_data(font->image.w, font->image.h);
697 if(!font->image.data)
699 memset(font->image.data, 255, font->image.w*font->image.h);
700 used_pixels = (unsigned *)malloc(font->image.w*sizeof(unsigned));
701 memset(used_pixels, 0, font->image.w*sizeof(unsigned));
702 used_glyphs = (char *)malloc(font->n_glyphs);
703 memset(used_glyphs, 0, font->n_glyphs);
705 for(cy=margin; cy+margin<font->image.h;)
710 unsigned best_score = 0;
711 unsigned target_h = 0;
713 /* Find the leftmost free pixel on this row. Also record the lowest
714 extent of glyphs to the left of the free position. */
715 for(; (cx+margin<font->image.w && used_pixels[cx]>cy); ++cx)
716 if(used_pixels[cx]-cy-padding>target_h)
717 target_h = used_pixels[cx]-cy-padding;
719 if(cx+margin>=font->image.w)
726 /* Count the free pixel at this position. */
727 for(w=0; (cx+w+margin<font->image.w && used_pixels[cx+w]<=cy); ++w) ;
729 /* Find a suitable glyph to put here. */
730 for(i=0; i<font->n_glyphs; ++i)
734 g = &font->glyphs[i];
735 if(!used_glyphs[i] && g->image.w<=w)
739 /* Prefer glyphs that would reach exactly as low as the ones left
740 of here. This aims to create a straight edge at the bottom for
741 lining up further glyphs. */
742 score = g->image.h+padding;
743 if(g->image.h==target_h)
762 used_glyphs[glyph-font->glyphs] = 1;
766 for(y=0; y<glyph->image.h; ++y) for(x=0; x<glyph->image.w; ++x)
768 if(cx+x>=font->image.w || cy+y>=font->image.h)
770 font->image.data[cx+x+(cy+y)*font->image.w] = 255-glyph->image.data[x+y*glyph->image.w];
772 for(x=0; x<glyph->image.w+2*padding; ++x)
774 if(cx+x<padding || cx+x>=font->image.w+padding)
776 if(used_pixels[cx+x-padding]<cy+glyph->image.h+padding)
777 used_pixels[cx+x-padding] = cy+glyph->image.h+padding;
780 if(cy+glyph->image.h+margin>used_h)
781 used_h = cy+glyph->image.h+margin;
784 /* Trim the image to the actually used size, in case the original estimate
785 was too pessimistic. */
786 font->image.h = round_to_pot(used_h);
794 int save_defs(const char *fn, const Font *font)
799 out = fopen(fn, "w");
802 fprintf(stderr, "Couldn't open %s\n",fn);
806 fprintf(out, "# Image/font info:\n");
807 fprintf(out, "# width height size ascent descent\n");
808 fprintf(out, "font %d %d %d %d %d\n", font->image.w, font->image.h, font->size, font->ascent, font->descent);
809 fprintf(out, "\n# Glyph info:\n");
810 fprintf(out, "# code x y width height offset_x offset_y advance\n");
811 for(i=0; i<font->n_glyphs; ++i)
813 const Glyph *g = &font->glyphs[i];
814 fprintf(out, "glyph %u %u %u %u %u %d %d %d\n", g->code, g->x, g->y, g->image.w, g->image.h, g->offset_x, g->offset_y, g->advance);
816 fprintf(out, "\n# Kerning info:\n");
817 fprintf(out, "# left right distance\n");
818 for(i=0; i<font->n_kerning; ++i)
820 const Kerning *k = &font->kerning[i];
821 fprintf(out, "kern %u %u %d\n", k->left_code, k->right_code, k->distance);
829 int save_png(const char *fn, const Image *image, char alpha)
843 out = fopen(fn, "wb");
846 fprintf(stderr, "Couldn't open %s\n",fn);
851 pngs = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
854 fprintf(stderr, "Error writing PNG file\n");
857 pngi = png_create_info_struct(pngs);
860 png_destroy_write_struct(&pngs, NULL);
861 fprintf(stderr, "Error writing PNG file\n");
865 png_init_io(pngs, out);
866 rows = (png_byte **)malloc(image->h*sizeof(png_byte *));
869 data2 = (png_byte *)alloc_image_data(image->w*2, image->h);
872 for(i=0; i<image->w*image->h; ++i)
875 data2[i*2+1] = 255-image->data[i];
877 for(i=0; i<image->h; ++i)
878 rows[i] = (png_byte *)(data2+i*image->w*2);
879 color = PNG_COLOR_TYPE_GRAY_ALPHA;
883 for(i=0; i<image->h; ++i)
884 rows[i] = (png_byte *)(image->data+i*image->w);
885 color = PNG_COLOR_TYPE_GRAY;
887 png_set_IHDR(pngs, pngi, image->w, image->h, 8, color, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
888 png_set_rows(pngs, pngi, rows);
889 png_write_png(pngs, pngi, PNG_TRANSFORM_IDENTITY, NULL);
890 png_destroy_write_struct(&pngs, &pngi);
896 printf("Saved %dx%d PNG image to %s\n", image->w, image->h, fn);