-
Notifications
You must be signed in to change notification settings - Fork 196
/
JIC.js
83 lines (68 loc) · 3.26 KB
/
JIC.js
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
/*!
* JIC JavaScript Library v1.0
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality){
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL("image/jpeg", quality);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @return {String} file_input_name The name of the input that the server will receive with the file
* @return {String} filename The name of the file that will be sent to the server
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type= 'image/jpeg';
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState != 4) {
console.log("ERROR uploading image..." + this.responseText);
} else {
console.log("IMAGE UPLOADED SUCCESFULLY..."+this.responseText);
}
};
}
};