Module: Lilimg

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

Class Method Summary collapse

Class Method Details

.jpeg_to_gif(buf, max_colors) ⇒ Object



23
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
# File 'ext/lilimg/lilimg.c', line 23

static VALUE jpeg_to_gif(VALUE self, VALUE buf, VALUE max_colors) {
  rb_check_type(buf, T_STRING);

  int maxColors = INT2NUM(max_colors);
  int size = RSTRING_LEN(buf);
  unsigned char * jpeg = (unsigned char *)StringValuePtr(buf);

  if (jpeg[0] != 0xFF || jpeg[1] != 0xD8) {
    rb_raise(rb_eRuntimeError, "Not a JPEG image (%x %x should be FF D8)!", jpeg[0], jpeg[1]);
    return Qnil;
  }

  njInit();

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

  unsigned char * pixels = njGetImage();
  if (!pixels) {
    free(jpeg);
    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) {
    free(jpeg);
    rb_raise(rb_eRuntimeError, "Cannot initialize memstream");
    return Qnil;
  }

  unsigned char * rgba = rgb_to_rgba(pixels, njGetWidth(), njGetHeight());
  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 = rb_str_new(out, bufsize);

  // free(jpeg); <-- this will cause all sorts of errors (FIXME)
  free(rgba);
  free(out);
  njDone();

  return rstr;
}