UNPKG

2.86 kBJavaScriptView Raw
1
2'use strict'
3
4var jpegjs = require('jpeg-js')
5
6var m = {}
7
8/**
9 * Decodes the given buffer and applies the right transformation
10 * Depending on the orientation, it may be a rotation and / or an horizontal flip
11 * @param buffer
12 * @param orientation
13 * @param quality
14 * @param module_callback
15 */
16m.do = function(buffer, orientation, quality, module_callback)
17{
18 try
19 {
20 var jpeg = jpegjs.decode(buffer)
21 }
22 catch(error)
23 {
24 module_callback(error, null, 0, 0)
25 return
26 }
27 var new_buffer = jpeg.data
28
29 var transformations = {
30 2: {rotate: 0, flip: true},
31 3: {rotate: 180, flip: false},
32 4: {rotate: 180, flip: true},
33 5: {rotate: 90, flip: true},
34 6: {rotate: 90, flip: false},
35 7: {rotate: 270, flip: true},
36 8: {rotate: 270, flip: false},
37 }
38
39 if (transformations[orientation].rotate > 0)
40 {
41 new_buffer = _rotate(new_buffer, jpeg.width, jpeg.height, transformations[orientation].rotate)
42 }
43 if (transformations[orientation].flip)
44 {
45 new_buffer = _flip(new_buffer, jpeg.width, jpeg.height)
46 }
47 var width = orientation < 5 ? jpeg.width : jpeg.height
48 var height = orientation < 5 ? jpeg.height : jpeg.width
49
50 var new_jpeg = jpegjs.encode({data: new_buffer, width: width, height: height}, quality)
51 module_callback(null, new_jpeg.data, width, height)
52}
53
54/**
55 * Rotates a buffer (degrees must be a multiple of 90)
56 * Inspired from Jimp (https://github.com/oliver-moran/jimp)
57 * @param buffer
58 * @param width
59 * @param height
60 * @param degrees
61 */
62var _rotate = function(buffer, width, height, degrees)
63{
64 var loops = degrees / 90
65 while (loops > 0)
66 {
67 var new_buffer = new Buffer(buffer.length)
68 var new_offset = 0
69 for (var x = 0; x < width; x += 1)
70 {
71 for (var y = height - 1; y >= 0; y -= 1)
72 {
73 var offset = (width * y + x) << 2
74 var pixel = buffer.readUInt32BE(offset, true)
75 new_buffer.writeUInt32BE(pixel, new_offset, true)
76 new_offset += 4
77 }
78 }
79 buffer = new_buffer
80 var new_height = width
81 width = height
82 height = new_height
83 loops -= 1
84 }
85 return buffer
86}
87
88/**
89 * Flips a buffer horizontally
90 * @param buffer
91 * @param width
92 * @param height
93 */
94var _flip = function(buffer, width, height)
95{
96 var new_buffer = new Buffer(buffer.length)
97 for(var x = 0; x < width; x += 1)
98 {
99 for(var y = 0; y < height; y += 1)
100 {
101 var offset = (width * y + x) << 2
102 var new_offset = (width * y + width - 1 - x) << 2
103 var pixel = buffer.readUInt32BE(offset, true)
104 new_buffer.writeUInt32BE(pixel, new_offset, true)
105 }
106 }
107 return new_buffer
108}
109
110module.exports = m