Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const ImageTypeEnum = Object.freeze({ JPG: 1, JPEG: 2, PNG: 3 })
- const ImageType = class {
- constructor(imageTypeEnum, suffix) {
- this.imageTypeEnum = imageTypeEnum
- this.suffix = suffix
- }
- }
- const ImageTypes = Object.freeze({
- JPG: new ImageType(ImageTypeEnum.JPG, 'jpg'),
- JPEG: new ImageType(ImageTypeEnum.JPEG, 'jpeg'),
- PNG: new ImageType(ImageTypeEnum.PNG, 'png')
- })
- export default class Base64Photo {
- constructor() {
- this.data = null
- this.imageType = null
- }
- decode(dataString) {
- let matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
- if (matches.length !== 3) {
- throw new Error(`Invalid image`)
- }
- this.setTypeEnum(matches[1])
- this.data = matches[2]
- }
- readFileInput(input) {
- if (input.files && input.files[0]) {
- let reader = new FileReader()
- reader.onload = function(e) {
- this.decode(e.target.result)
- }.bind(this)
- reader.readAsDataURL(input.files[0])
- }
- }
- setTypeEnum(type) {
- switch (type) {
- case 'image/jpg':
- this.imageType = ImageTypes.JPG
- break
- case 'image/jpeg':
- this.imageType = ImageTypes.JPEG
- break
- case 'image/png':
- this.imageType = ImageTypes.PNG
- break
- default:
- throw `Invalid image type: ${type}`
- }
- }
- getSuffix() {
- return this.imageType.suffix
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement