diff --git a/src/services/picture.ts b/src/services/picture.ts new file mode 100644 index 000000000..3f2ba3724 --- /dev/null +++ b/src/services/picture.ts @@ -0,0 +1,99 @@ +import { Injectable } from '@angular/core'; +import { Platform } from 'ionic-angular'; +import { ImagePicker } from '@ionic-native/image-picker'; +import { UploadFS } from 'meteor/jalik:ufs'; + +@Injectable() +export class PictureService { + constructor(private platform: Platform, + private imagePicker: ImagePicker) { + } + + select(): Promise { + if (!this.platform.is('cordova') || !this.platform.is('mobile')) { + return new Promise((resolve, reject) => { + try { + UploadFS.selectFile((file: File) => { + resolve(file); + }); + } + catch (e) { + reject(e); + } + }); + } + + return this.imagePicker.getPictures({maximumImagesCount: 1}).then((URL: string) => { + return this.convertURLtoBlob(URL); + }); + } + + convertURLtoBlob(url: string, options = {}): Promise { + return new Promise((resolve, reject) => { + const image = document.createElement('img'); + + image.onload = () => { + try { + const dataURI = this.convertImageToDataURI(image, options); + const blob = this.convertDataURIToBlob(dataURI); + const pathname = (new URL(url)).pathname; + const filename = pathname.substring(pathname.lastIndexOf('/') + 1); + const file = new File([blob], filename); + + resolve(file); + } + catch (e) { + reject(e); + } + }; + + image.src = url; + }); + } + + convertImageToDataURI(image: HTMLImageElement, {MAX_WIDTH = 400, MAX_HEIGHT = 400} = {}): string { + // Create an empty canvas element + const canvas = document.createElement('canvas'); + + var width = image.width, height = image.height; + + if (width > height) { + if (width > MAX_WIDTH) { + height *= MAX_WIDTH / width; + width = MAX_WIDTH; + } + } else { + if (height > MAX_HEIGHT) { + width *= MAX_HEIGHT / height; + height = MAX_HEIGHT; + } + } + + canvas.width = width; + canvas.height = height; + + // Copy the image contents to the canvas + const context = canvas.getContext('2d'); + context.drawImage(image, 0, 0, width, height); + + // Get the data-URL formatted image + // Firefox supports PNG and JPEG. You could check image.src to + // guess the original format, but be aware the using 'image/jpg' + // will re-encode the image. + const dataURL = canvas.toDataURL('image/png'); + + return dataURL.replace(/^data:image\/(png|jpg);base64,/, ''); + } + + convertDataURIToBlob(dataURI): Blob { + const binary = atob(dataURI); + + // Write the bytes of the string to a typed array + const charCodes = Object.keys(binary) + .map(Number) + .map(binary.charCodeAt.bind(binary)); + + // Build blob with typed array + return new Blob([new Uint8Array(charCodes)], {type: 'image/jpeg'}); + } +}