import { Injectable } from '@angular/core' ; import { Platform } from 'ionic-angular' ; import { ImagePicker } from 'ionic-native' ; import { UploadFS } from 'meteor/jalik:ufs' ; import { _ } from 'meteor/underscore' ; import { PicturesStore } from '../../../imports/collections' ; import { DEFAULT_PICTURE_URL } from '../../../imports/models' ; @ Injectable ( ) export class PictureService { constructor ( private platform ) { } select ( ) { if ( ! this . platform . is ( 'cordova' ) || ! this . platform . is ( 'mobile' ) ) { return new Promise ( ( resolve , reject ) => { try { UploadFS . selectFile ( ( file ) => { resolve ( file ) ; } ) ; } catch ( e ) { reject ( e ) ; } } ) ; } return ImagePicker . getPictures ( { maximumImagesCount : 1 } ) . then ( ( URL ) => { return this . convertURLtoBlob ( URL ) ; } ) ; } upload ( blob ) { return new Promise ( ( resolve , reject ) => { const metadata = _ . pick ( blob , 'name' , 'type' , 'size' ) ; if ( ! metadata . name ) { metadata . name = DEFAULT_PICTURE_URL ; } const upload = new UploadFS . Uploader ( { data : blob , file : metadata , store : PicturesStore , onComplete : resolve , onError : reject } ) ; upload . start ( ) ; } ) ; } convertURLtoBlob ( URL ) { return new Promise ( ( resolve , reject ) => { const image = document . createElement ( 'img' ) ; image . onload = ( ) => { try { const dataURI = this . convertImageToDataURI ( image ) ; const blob = this . convertDataURIToBlob ( dataURI ) ; resolve ( blob ) ; } catch ( e ) { reject ( e ) ; } } ; image . src = URL ; } ) ; } convertImageToDataURI ( image ) { const canvas = document . createElement ( 'canvas' ) ; canvas . width = image . width ; canvas . height = image . height ; const context = canvas . getContext ( '2d' ) ; context . drawImage ( image , 0 , 0 ) ; const dataURL = canvas . toDataURL ( 'image/png' ) ; return dataURL . replace ( /^data:image\/(png|jpg);base64,/ , '' ) ; } convertDataURIToBlob ( dataURI ) { const binary = atob ( dataURI ) ; const charCodes = Object . keys ( binary ) . map < number > ( Number ) . map < number > ( binary . charCodeAt . bind ( binary ) ) ; return new Blob ( [ new Uint8Array ( charCodes ) ] , { type : 'image/jpeg' } ) ; } }