-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageTools.js
104 lines (89 loc) · 3.18 KB
/
ImageTools.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//Ver 0.1
class ImageTools{
constructor(src,onload,whidth_height_xoffset_yoffset_AsArray,resizeWidthHeight_AsArray,renameTo_){
//this.canvas;
//this.context;
//this.data;
var me=this;
renameTo_=renameTo_ || ("imageToCanvas_"+src);
this.rawdata=null;
this.alreadyExists=false;
var canvas;
if (document.getElementById(renameTo_)){
canvas=document.getElementById(renameTo_);
this.alreadyExists=true;
}
else
canvas= this.canvas= document.createElement('canvas');
var c2d=this.context=canvas.getContext("2d");
canvas.id = renameTo_ ;
var X=whidth_height_xoffset_yoffset_AsArray;
var img=new Image();
img.onload=function(){
if (!X)
X=[img.width,img.height,0,0];
else{
var j=X;
j[0]=j[0]||(j[1]*img.height/img.width);
j[1]=j[1]||(j[0]*img.height/img.width);
}
canvas.width=X[0]||img.width;
canvas.height=X[1]||img.height;
if (!resizeWidthHeight_AsArray)
c2d.drawImage(img,X[2]||0,X[3]||0);
else{
var j=resizeWidthHeight_AsArray;
j[0]=j[0]||(j[1]*img.height/img.width);
j[1]=j[1]||(j[0]*img.height/img.width);
c2d.drawImage(img,X[2]||0,X[3]||0,j[0],j[1]);
}
me.rawdata=me.context.getImageData(0,0,canvas.width,canvas.height);
if (onload)
onload(me);
//hints
//document.getElementsByTagName("body")[0].appendChild(canvas)
};
img.src=src;
}
//typeOfExeclude: 0 none, -1 ex-alpha, 1,2,3 for channel Red Green or Blue
//returns result
createData(typeOfExeclude=0,divideBy=1,add_=0){
//console.log("test");
var r=[];var i,j,k;
var w_=this.rawdata.width;
var h_=this.rawdata.height;
var d_=this.rawdata.data;
for (i=0;i<w_;i++){
r[i]=[];
for (j=0;j<h_;j++){
k=j*w_*4+i*4;
switch(typeOfExeclude) {
//execlude nothing
case 0:
r[i][j]=[
d_[k]/divideBy+add_
,d_[k+1]/divideBy+add_
,d_[k+2]/divideBy+add_
,d_[k+3]/divideBy+add_
];
break;
//exclude alpha
case -1:
r[i][j]=[
d_[k]/divideBy+add_
,d_[k+1]/divideBy+add_
,d_[k+2]/divideBy+add_
];
break;
//choose specific channel
default:
r[i][j]=[d_[k+typeOfExeclude]/divideBy+add_];
break;
}
}
}
//return result
return r;
}
transpose = m => m[0].map((x,i) => m.map(x => x[i]))
}