Permalink
Browse files

Step 13.5: Create PictureService with utils for files

  • Loading branch information...
dotansimha authored and darkbasic committed Jan 24, 2017
1 parent dbde949 commit 27f953c61b7d1511d50a9b450606953894d6ad0e
Showing with 99 additions and 0 deletions.
  1. +99 −0 src/services/picture.ts
View
@@ -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<File> {
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<File> {
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>(Number)
.map<number>(binary.charCodeAt.bind(binary));
// Build blob with typed array
return new Blob([new Uint8Array(charCodes)], {type: 'image/jpeg'});
}
}

0 comments on commit 27f953c

Please sign in to comment.