font.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * This program is free software; you can redistribute it and/or
  3. * modify it under the terms of the GNU General Public License
  4. * as published by the Free Software Foundation; either version 2
  5. * of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. * Author: g0tsu
  12. * Email: g0tsu at dnmx.0rg
  13. */
  14. #include <libcaptcha.h>
  15. #include <stdio.h>
  16. #include <errno.h>
  17. #include <stdlib.h>
  18. #include <stb_truetype.h>
  19. lc_fontBuffer * lc_create_font(const char *filename) {
  20. FILE *font_fd = fopen(filename, "rb");
  21. size_t font_size = 0;
  22. lc_fontBuffer *font;
  23. stbtt_fontinfo *info;
  24. if (font_fd == NULL) {
  25. return NULL;
  26. }
  27. fseek(font_fd, 0, SEEK_END);
  28. font_size = ftell(font_fd);
  29. fseek(font_fd, 0, SEEK_SET);
  30. if (font_size < 8) {
  31. return NULL;
  32. }
  33. if ((info = malloc(sizeof(*info))) == NULL) {
  34. errno = ENOMEM;
  35. return NULL;
  36. }
  37. if ((font = malloc(sizeof(*font))) == NULL) {
  38. errno = ENOMEM;
  39. return NULL;
  40. }
  41. if ((font->buffer = malloc(font_size)) == NULL) {
  42. errno = ENOMEM;
  43. free(info);
  44. free(font);
  45. return NULL;
  46. }
  47. fread(font->buffer, font_size, 1, font_fd);
  48. fclose(font_fd);
  49. font->type = LC_TYPE_FONT;
  50. font->info = info;
  51. if (!stbtt_InitFont(font->info, font->buffer, 0)) {
  52. errno = EINVAL;
  53. lc_free(font);
  54. return NULL;
  55. }
  56. return font;
  57. }
  58. lc_bmpGlyph * lc_create_glyph(lc_fontBuffer *font, const int glyph, const int line_height) {
  59. int w, h;
  60. float scale;
  61. unsigned char *bitmap;
  62. lc_bmpGlyph *bg;
  63. if ((bg = malloc(sizeof(*bg))) == NULL) {
  64. errno = ENOMEM;
  65. return NULL;
  66. }
  67. scale = stbtt_ScaleForPixelHeight(font->info, line_height);
  68. bg->buffer = stbtt_GetCodepointBitmap(font->info, 0, scale, glyph, &w, &h, 0, 0);
  69. bg->type = LC_TYPE_GLYPH;
  70. bg->w = w;
  71. bg->h = h;
  72. return bg;
  73. }