images.js
2.68 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/**
* 图片处理
* @author: 梁校松
* @date: 2016/4/25
*/
'use strict';
const _ = require('lodash');
const // domain = '.static.yhbimg.com',
defaultImage = '/2015/08/25/02/01dd632a6e07bfef457ce4beda21dd6413.png',
qiniuDomain = 'yhfair.qiniudn.com',
domainList = {
'01': ['img10.static.yhbimg.com', 'img11.static.yhbimg.com'],
'02': ['img12.static.yhbimg.com', 'img13.static.yhbimg.com'],
'yhb-head': 'head.static.yhbimg.com'
};
const regexp = /(?:\{)([a-zA-z][^\s\}]+)(?:\})/g;
const myReplace = (tem, data) => {
return tem.replace(regexp, function(fullMatch, capture) {
if (data[capture]) {
return data[capture];
} else {
return fullMatch;
}
});
};
const makeBaseUrl = (domain, key) =>{
encodeURIComponent(key).replace('%2F', '/');
return `http://${domain}/${key}`;
};
const makeTemplateRequest = url => {
let ops = ['{mode}', 'w/{width}', 'h/{height}'];
if (ops.length === 0) {
return url;
}
return url + '?imageView/' + ops.join('/');
};
const getImgTemplateUrl = (fileName, mode, domain) =>{
// 默认值
if (!mode) {
mode = 1;
}
if (!domain) {
domain = null;
}
if (domain === null) {
domain = qiniuDomain;
}
let baseUrl = makeBaseUrl(domain, fileName);
return makeTemplateRequest(baseUrl);
};
const getDomain = (bucket, fileName) => {
let domain = '';
if (bucket in domainList) {
domain = domainList.bucket;
} else {
let node = fileName.substr(15, 2);
if (node in domainList) {
let urlList = domainList[node];
let nodeNum = _.random(urlList.length - 1);
domain = urlList[nodeNum];
}
}
return domain;
};
const url = (fileName, bucket, mode) =>{
// 默认值
if (!mode) {
mode = 1;
}
if (!bucket) {
bucket = 'yhfair';
}
let domain = getDomain(bucket, fileName);
return getImgTemplateUrl(bucket + fileName, mode, domain);
};
const template = (fileName, bucket, mode) => {
// 默认值
if (!mode) {
mode = 1;
}
if (!bucket) {
bucket = 'yhfair';
}
return url(fileName, bucket, mode);
};
exports.getImageUrl = (fileName, width, height, mode, bucket) => {
// 默认值
if (!mode) {
mode = 2;
}
if (!bucket) {
bucket = 'goodsimg';
}
if (typeof(fileName) !== 'string') {
return template(defaultImage, bucket, mode);
}
if (fileName.indexOf('http://') !== 0) {
fileName = template(fileName, bucket, mode);
}
return myReplace(fileName, {width: width, height: height, mode: mode});
};