Skip to content

Commit

Permalink
Step 12.3: Create PictureService with utils for files
Browse files Browse the repository at this point in the history
  • Loading branch information
dotansimha authored and DAB0mB committed Mar 23, 2017
1 parent 8c08957 commit 5e36bd4
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions src/services/picture.ts
@@ -0,0 +1,80 @@
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { ImagePicker } from 'ionic-native';
import { UploadFS } from 'meteor/jalik:ufs';

@Injectable()
export class PictureService {
constructor(private platform: Platform) {
}

select(): Promise<Blob> {
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 ImagePicker.getPictures({maximumImagesCount: 1}).then((URL: string) => {
return this.convertURLtoBlob(URL);
});
}

convertURLtoBlob(URL: string): Promise<Blob> {
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: HTMLImageElement): string {
// Create an empty canvas element
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;

// Copy the image contents to the canvas
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);

// 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 5e36bd4

Please sign in to comment.