Created
October 1, 2020 08:57
-
-
Save dmitry-stepanenko/f3dc2a83ffbbaa8bb4080f4bb1fef296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { ActionSheetController, Platform } from '@ionic/angular'; | |
import { AppService } from './app.service'; | |
import { Camera } from '@ionic-native/camera/ngx'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class GetPhotoService { | |
constructor( | |
private actionSheetCtrl: ActionSheetController, | |
private appService: AppService, | |
private platform: Platform, | |
private camera: Camera | |
) { } | |
/** | |
* Opens an action sheet with options how to take photo. | |
* @returns selected/taken photo as base64. Will return `null` if nothing is selected | |
* @param loaderOptions optionally you can provide an options to config how the loader should show. | |
* if `show` set to true, will show a loader once photo source is selected. | |
* Also you can config `hideAfterGet` param - if set to false, loader won't hide after image is successfully loaded from the photo source. | |
* It can be useful when you need to make additional processing to the photo and hide a loader once everything is done | |
*/ | |
async openImageOptionPrompt(loaderOptions?: { show: boolean; hideAfterGet: boolean }): Promise<string | null> { | |
const source = this.camera.PictureSourceType; | |
const actionSheet = await this.actionSheetCtrl.create({ | |
buttons: [ | |
{ | |
text: 'From Gallery', | |
role: source.PHOTOLIBRARY.toString(), | |
icon: 'image-outline', | |
}, | |
{ | |
text: 'From Camera', | |
role: source.CAMERA.toString(), | |
icon: 'camera-outline', | |
}, | |
{ | |
text: 'Cancel', | |
icon: 'close', | |
role: 'cancel', | |
}, | |
] | |
}); | |
actionSheet.present(); | |
const sourceType = await actionSheet.onDidDismiss(); | |
if (+sourceType.role === source.CAMERA || +sourceType.role === source.PHOTOLIBRARY) { | |
if (loaderOptions && loaderOptions.show) { | |
this.appService.showLoader(); | |
} | |
const path = await this.takePicture(+sourceType.role); | |
if (loaderOptions && loaderOptions.hideAfterGet) { | |
this.appService.hideLoader(); | |
} | |
return path; | |
} | |
} | |
private async takePicture(sourceType: number): Promise<string | null> { | |
if (!this.platform.is('cordova')) { | |
throw new Error('Incompatible platform'); | |
} | |
try { | |
const image = await this.camera.getPicture({ | |
sourceType, | |
encodingType: this.camera.EncodingType.JPEG, | |
destinationType: this.camera.DestinationType.DATA_URL, | |
}) | |
return image; | |
} catch (error) { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment