Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. const ImageTypeEnum = Object.freeze({ JPG: 1, JPEG: 2, PNG: 3 })
  2. const ImageType = class {
  3. constructor(imageTypeEnum, suffix) {
  4. this.imageTypeEnum = imageTypeEnum
  5. this.suffix = suffix
  6. }
  7. }
  8. const ImageTypes = Object.freeze({
  9. JPG: new ImageType(ImageTypeEnum.JPG, 'jpg'),
  10. JPEG: new ImageType(ImageTypeEnum.JPEG, 'jpeg'),
  11. PNG: new ImageType(ImageTypeEnum.PNG, 'png')
  12. })
  13.  
  14. export default class Base64Photo {
  15. constructor() {
  16. this.data = null
  17. this.imageType = null
  18. }
  19.  
  20. decode(dataString) {
  21. let matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
  22. if (matches.length !== 3) {
  23. throw new Error(`Invalid image`)
  24. }
  25.  
  26. this.setTypeEnum(matches[1])
  27. this.data = matches[2]
  28. }
  29.  
  30. readFileInput(input) {
  31. if (input.files && input.files[0]) {
  32. let reader = new FileReader()
  33.  
  34. reader.onload = function(e) {
  35. this.decode(e.target.result)
  36. }.bind(this)
  37.  
  38. reader.readAsDataURL(input.files[0])
  39. }
  40. }
  41.  
  42. setTypeEnum(type) {
  43. switch (type) {
  44. case 'image/jpg':
  45. this.imageType = ImageTypes.JPG
  46. break
  47. case 'image/jpeg':
  48. this.imageType = ImageTypes.JPEG
  49. break
  50. case 'image/png':
  51. this.imageType = ImageTypes.PNG
  52. break
  53. default:
  54. throw `Invalid image type: ${type}`
  55. }
  56. }
  57.  
  58. getSuffix() {
  59. return this.imageType.suffix
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement