/
react-image-compressor.js
214 lines (163 loc) · 4.71 KB
/
react-image-compressor.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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*! Copyright (c) 2016 Naufal Rabbani (http://github.com/BosNaufal)
* Licensed Under MIT (http://opensource.org/licenses/MIT)
*
* React Image Compressor @ Version 0.0.1
*
* refs:
* https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
* https://davidwalsh.name/convert-canvas-image
* https://beta.webcomponents.org/element/3mp3ri0r/cpol-image
*
*/
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import base64toblob from 'base64toblob';
class ImageCompressor extends React.Component {
constructor() {
super()
this.state = {
file: {},
result: {},
reader: {},
imgSrc: "",
}
this._handleChange = this._handleChange.bind(this)
this._fileOnLoad = this._fileOnLoad.bind(this)
this._redraw = this._redraw.bind(this)
this._drawImage = this._drawImage.bind(this)
}
_handleChange(e){
// If There's no file choosen
let file = e.target.files[0]
if(!file) return false
// get the file
this.setState({ file }, () => {
// Validation
let type = this.state.file.type
let valid = type.indexOf("image") !== -1
if(!valid) throw "File Type Is Not Supported. Upload an image instead"
// Make new FileReader
this.setState({ reader: new FileReader() }, () => {
// Convert the file to base64 text
this.state.reader.readAsDataURL(this.state.file)
// on reader load something...
this.state.reader.onload = this._fileOnLoad
})
})
}
/*
Draw And Compress The Image
@params {String} imgUrl
*/
_drawImage(imgUrl, rerender) {
// Recreate Canvas Element
let canvas = document.createElement('canvas')
this.setState({ canvas }, () => {
// Set Canvas Context
let ctx = this.state.canvas.getContext('2d')
// Create New Image
let img = new Image()
img.src = imgUrl
// Image Size After Scaling
let scale = this.props.scale / 100
let width = img.width * scale
let height = img.height * scale
// Set Canvas Height And Width According to Image Size And Scale
this.state.canvas.setAttribute('width', width)
this.state.canvas.setAttribute('height', height)
ctx.drawImage(img, 0, 0, width, height)
// Quality Of Image
let quality = this.props.quality ? (this.props.quality / 100) : 1
// If all files have been proceed
let base64 = this.state.canvas.toDataURL('image/jpeg', quality)
let fileName = this.state.result.file.name
let lastDot = fileName.lastIndexOf(".")
fileName = fileName.substr(0,lastDot) + '.jpeg'
let objToPass = {
canvas: this.state.canvas,
original: this.state.result,
compressed: {
blob: this._toBlob(base64),
base64: base64,
name: fileName,
file: this._buildFile(base64, fileName)
},
}
objToPass.compressed.size = Math.round(objToPass.compressed.file.size / 1000)+' kB'
objToPass.compressed.type = "image/jpeg"
this.props.onDone(objToPass)
})
}
/*
Redraw the canvas
*/
_redraw() {
let { result: { base64 } } = this.state
if(base64) {
this._drawImage(base64, true)
}
}
/*
when the file in loaded
*/
_fileOnLoad() {
// the file
let { file, reader } = this.state
// make a fileinfo object
let fileinfo = {
name: file.name,
type: file.type,
size: Math.round(file.size / 1000)+' kb',
base64: reader.result,
file: file
}
// push it to the state
this.setState({ result: fileinfo }, () => {
// drawImage
this._drawImage(this.state.result.base64)
})
}
// Convert Base64 to Blob
_toBlob (imgUrl) {
let blob = base64toblob(imgUrl.split(',')[1], "image/jpeg")
let url = window.URL.createObjectURL(blob)
return url
}
// Convert Blob To File
_buildFile (blob, name) {
return new File([blob], name)
}
componentWillReceiveProps(nextProps) {
let { quality, scale } = this.props
let theStateHasChanged = quality !== nextProps.quality || scale !== nextProps.scale
if(theStateHasChanged) {
this._redraw()
}
}
componentDidMount() {
}
render(){
let { className, id } = this.props
return (
<input
id={ id ? id : null }
className={ className ? className : null }
type="file"
onChange={ this._handleChange } />
)
}
}
// The Props
ImageCompressor.propTypes = {
id: PropTypes.string,
className: PropTypes.string,
scale: PropTypes.number.isRequired,
quality: PropTypes.number.isRequired,
onDone: PropTypes.func
}
ImageCompressor.defaultProps = {
scale: 100,
quality: 75,
onDone: () => {},
}
export default ImageCompressor;