forked from DMarby/picsum-photos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageProcessor.js
76 lines (63 loc) · 2.73 KB
/
imageProcessor.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
module.exports = exports = function (sharp, path, config, fs) {
var ImageProcessor = {
'getProcessedImage': function (width, height, gravity, gray, blur, filePath, shortName, callback) {
gravity = ImageProcessor.getGravity(gravity)
ImageProcessor.getAndCheckDestination(width, height, gravity, blur, filePath, gray ? 'gray-' : '', shortName, function (exists, destination) {
if (exists) {
return callback(null, destination)
}
ImageProcessor.imageResize(width, height, gravity, filePath, destination, gray, blur, function (error, destination) {
if (error) {
ImageProcessor.deleteFile(destination)
return callback(error)
}
callback(null, destination)
})
})
},
'getGravity': function(gravity) {
gravity = gravity ? gravity : 'center'
gravity = gravity == 'centre' ? 'center' : gravity
return gravity
},
'getAndCheckDestination': function (width, height, gravity, blur, filePath, prefix, shortName, callback) {
var destination = shortName ? ImageProcessor.getShortDestination(width, height, gravity, blur, filePath, prefix) : ImageProcessor.getDestination(width, height, gravity, blur, filePath, prefix)
fs.exists(destination, function (exists) {
callback(exists, destination)
})
},
'getDestination': function (width, height, gravity, blur, filePath, prefix) {
return config.cache_folder_path + '/' + prefix + path.basename(filePath, path.extname(filePath)) + '-' + width + 'x' + height + '-' + gravity + (blur ? '-blur' : '') + '.jpeg'
},
'getShortDestination': function (width, height, gravity, blur, filePath, prefix) {
return config.cache_folder_path + '/' + prefix + width + '^' + height + '-' + gravity + (blur ? '-blurred' : '') + '.jpeg'
},
'imageResize': function (width, height, gravity, filePath, destination, gray, blur, callback) {
try {
var image = sharp(filePath).rotate().resize(width, height).crop(sharp.gravity[gravity]);
if (gray) {
image.grayscale()
}
if (blur) {
image.blur(10)
}
image.jpeg().progressive().toFile(destination, function (error) {
callback(error, destination)
})
} catch (error) {
callback(error, null)
}
},
'deleteFile': function (destination) {
fs.unlink(destination, function (error) {
console.log('Error, deleted file')
})
},
'getWidthAndHeight': function (params, square, callback) {
var width = square ? params.size : params.width
var height = square ? params.size : params.height
callback(width, height)
}
}
return ImageProcessor
}