Ionic Upload image and take from camera and send data to API
1. Install camera Plugin
npm install @capacitor/camera
npx cap sync
2. create function for take photo and select image
selectedImage: string;
async openCamera() {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Base64
});
this.selectedImage = `data:image/jpeg;base64,${image.base64String}`;
}
3. Create Ionic UI for click this function and show Image
<ion-button type="button" (click)="openCamera()"><ion-icon slot="start" name="camera"></ion-icon> Take Photo </ion-button>
@if(selectedImage){
<ion-img [src]="selectedImage" style="width:150px; height:150px;"></ion-img>
}
4. Upload image to API
first image convert base64 to blob image
Now, create API function and convert image to formdata
first image convert base64 to blob image
base64ToBlob(base64Data: string, contentType: string): Blob {
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length).fill(0).map((_, i) => byteCharacters.charCodeAt(i));
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: contentType });
}
uploadImage(){
let splitImage = this.selectedImage.split(',');
const imageBlob = this.base64ToBlob(splitImage[1], 'image/jpeg');
const imageName = `${Date.now()}.jpeg`;
const formData = new FormData();
formData.append('image', imageBlob, imageName);
this.http.post('/upload-image', formdata)
.subscribe((res)=>{
console.log("result", res);
})
}
// html
<ion-button type="button" (click)="uploadImage()">Upload Image</ion-button>


Login to leave a comment.