0 /* See LICENSE file for copyright and license details. */

1 #if defined(TERMINAL_IMG_VIEWER) && defined(__has_include) && !(__has_include(<stb_image.h>))

2 #warning Unable to build built-in image viewer, stb_image header not found

3 #endif

4 #include "img.h"

5

6 #ifdef TERMINAL_IMG_VIEWER

7 #define STB_IMAGE_IMPLEMENTATION

8 #include <stb_image.h>

9 #include <termbox.h>

10 #include "gemini.h"

11

12

13 int color_abs(int c, int x, int i) {

14 return abs(c-=i>215?i*10-2152:x*40+!!x*55);

15 }

16

17 int color(uint8_t r, uint8_t g, uint8_t b) {

18 int m = 0, t = 0;

19 int i = 240, l = 240;

20 while (i--) {

21 t = color_abs(r, i/36, i) + color_abs(g, i/6%!,(MISSING) i) + color_abs(b, i%!,(MISSING) i);

22 if (t < l) {

23 l = t;

24 m = i;

25 }

26 }

27 i=m+16;

28 return i;

29 }

30

31 int color16(int r, int g, int b) {

32 return (r*6/256)*36 + (g*6/256)*6 + (b*6/256);

33 }

34

35 int average_pixel(uint8_t* data, int x, int y, int w, int h, float ratio, int c16) {

36 int pixels = 0;

37 int r = 0, g = 0, b = 0;

38 float precision = 2;

39 for (int i = x - ratio/precision; i < x + ratio/precision; i++) {

40 if (i >= w || i < 0) continue;

41 for (int j = y - ratio/precision; j < y + ratio/precision; j++) {

42 if (j >= h || j < 0) continue;

43 r += data[(i + j * w)*3];

44 g += data[(i + j * w)*3+1];

45 b += data[(i + j * w)*3+2];

46 pixels++;

47 }

48 }

49 if (pixels == 0) return 0;

50 return c16?color16(r/pixels, g/pixels, b/pixels):

51 color(r/pixels, g/pixels, b/pixels);

52 }

53

54 int img_display(uint8_t* data, int w, int h, int offsety) {

55 int c16 = 0;//!client.c256;

56

57 double w_ratio = (double)w/(tb_width());

58 double h_ratio = (double)h/((tb_height()-offsety-2)*2);

59 if (w_ratio < h_ratio)

60 w_ratio = h_ratio;

61 else

62 h_ratio = w_ratio;

63 int _x = 0;

64 int _y = 0;

65 for (double x = 0; x < (double)w; x += w_ratio) {

66 for (double y = 0; y < (double)h; y += h_ratio) {

67 tb_print(_x, _y+offsety,

68 average_pixel(data, x, y+1, w, h, h_ratio, c16),

69 average_pixel(data, x, y, w, h, h_ratio, c16),

70 "▄");

71 y += h_ratio;

72 _y++;

73 }

74 _y = 0;

75 _x++;

76 }

77 return 0;

78 }

79

80 #else

81 typedef int remove_iso_warning;

82 #endif

83