Module: Lilimg

Defined in:
lib/lilimg.rb,
ext/lilimg/lilimg.c

Class Method Summary collapse

Class Method Details

.jpeg_to_gif(buf) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'ext/lilimg/lilimg.c', line 24

static VALUE jpeg_to_gif(VALUE self, VALUE buf) {
  rb_check_type(buf, T_STRING);
  int size = RSTRING_LEN(buf);
  char * jpeg = StringValuePtr(buf);

  unsigned int first, second;
  first = jpeg[0];
  second = jpeg[1];

  if (first != 0xFF || second != 0xD8) {
    rb_raise(rb_eRuntimeError, "Not a JPEG image!");
    return Qnil; 
  }

  njInit();

  if (njDecode(jpeg, size)) {
    free((void*)jpeg);
    rb_raise(rb_eRuntimeError, "Error decoding input file (size %d)", size);
    return Qnil;
  }

  free((void*)jpeg);

  unsigned char * pixels = njGetImage();
  if (!pixels) {
    rb_raise(rb_eRuntimeError, "Couldn't decode image.");
    return Qnil;
  }

  char * out;
	size_t bufsize;
	FILE * fp = open_memstream(&out, &bufsize);
	// FILE * fp = fopen("output.gif", "wb");

  if (!fp) {
    rb_raise(rb_eRuntimeError, "Cannot initialize memstream");
    return Qnil;
  }

  unsigned char * rgba = rgb_to_rgba(pixels, njGetWidth(), njGetHeight());
  int maxColors = 8;

  jo_gif_t gif = jo_gif_start(fp, njGetWidth(), njGetHeight(), 0, maxColors); 
  jo_gif_frame(&gif, rgba, 0, 0);
  jo_gif_end(&gif);

  VALUE rstr;
  rstr = rb_str_new(out, bufsize);

  free(rgba);
  free(out);
  njDone();

  return rstr;
}