summaryrefslogtreecommitdiff
path: root/js/image.js
blob: ef58f4bb0278cb9228a350a5db702a52ad65db5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var gif, img
var imageURL = null

function loadImage(imageURL, callback) {
  var imageURL = proxify( imageURL );
  window.imageURL = imageURL

  window.gif = window.img = null

	if (! imageURL) {
		window.gif = null
		window.img = null
		callback()
	}
  else if (imageURL.substr(-3) === "gif") {
    window.gif = GIF(imageURL);
    // gif.on("error", tryToLoadNextImage);
    // gif.on("rendered", trackLoadTime);
    gif.on("rendered", callback);
		gif.render();
  }
  else {
    window.img = new Image();
    // img.addEventListener("error", tryToLoadNextImage);
    img.addEventListener("load", callback);
    img.crossOrigin = "anonymous";
    img.src = imageURL;
  }
}

function giveImage(t) {
  if (window.gif) {
    return gif.frames[gif.currentFrame(t)];
  } else {
    return img;
  }
}

function proxify (url) {
  if (url.indexOf("http") == 0)
    return "/cgi-bin/proxy?" + url.replace(/^https/, "http");
  else
    return url
}

function filesize(n) {
  if (n < 1e3) return n + " bytes"
  if (n < 1e6) return decimalString(n/1e3) + " kb"
  if (n < 1e9) return decimalString(n/1e6) + " mb"
  return "WAY TOO BIG DUDE"
}
function decimalString(n){
  var m = Math.floor(n);
  return m + "." + Math.round((n-m)*10)
}
function noop(){}

function uploadImage(opt){
  if (! opt.blob || ! opt.filename) return;
  
  opt.username = opt.username || "";
  opt.success = opt.success || noop;
  opt.error = opt.error || noop;

  var form = new FormData();

  form.append("username", opt.username);
  form.append("filename", opt.filename);
  form.append("qqfile", opt.blob);

  var req = new XMLHttpRequest();
  req.open("POST", "/cgi-bin/im/shader/upload");
  req.onload = function(event) {
    if (req.status == 200) {
      var res = JSON.parse(req.responseText);
      if (res.success) {
        opt.success(res);
      }
      else {
        opt.error(res);
      }      
    } else {
      opt.error({ success: false, error: req.status });
    }
  };
  req.send(form);
}