compress image of publications and chat

This commit is contained in:
Eudes Inácio
2023-08-28 16:36:31 +01:00
parent fe6614a37e
commit 8525fcb8f6
7 changed files with 368 additions and 28 deletions
@@ -125,24 +125,48 @@ export class NewPublicationPage implements OnInit {
// in use
async takePicture() {
const capturedImage = await Camera.getPhoto({
quality: 50,
// allowEditing: true,
resultType: CameraResultType.Uri,
resultType: CameraResultType.Base64,
source: CameraSource.Camera
});
const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
this.capturedImage = 'data:image/jpeg;base64,' +capturedImage.base64String;
this.capturedImageTitle = 'foto';
const compressedImage = await this.compressImageBase64(
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
console.log('taked: ', picture)
this.capturedImage = picture
});
}
this.convertBlobToBase64Worker.postMessage(blob);
this.convertBlobToBase64Worker.onmessage = async (oEvent)=> {
this.capturedImage = oEvent.data
this.capturedImageTitle = 'foto'
async laodPicture() {
const capturedImage = await Camera.getPhoto({
quality: 90,
resultType: CameraResultType.Base64,
source: CameraSource.Photos
});
this.capturedImage = 'data:image/jpeg;base64,' +capturedImage.base64String;
this.capturedImageTitle = 'foto';
const compressedImage = await this.compressImageBase64(
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
console.log('Selected: ', picture)
this.capturedImage = picture
});
}
}
imageSize(image) {
var canvas = document.createElement('canvas');
@@ -165,7 +189,7 @@ export class NewPublicationPage implements OnInit {
});
// in use
/* // in use
async laodPicture() {
const capturedImage = await Camera.getPhoto({
@@ -185,7 +209,7 @@ export class NewPublicationPage implements OnInit {
}
}
} */
@@ -374,4 +398,41 @@ export class NewPublicationPage implements OnInit {
deletePublicationImage() {
this.publication.FileBase64 = ""
}
async compressImageBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise((resolve, reject) => {
const image = new (window as any).Image();
image.src = base64String;
image.onload = async () => {
const canvas = document.createElement('canvas');
let newWidth = image.width;
let newHeight = image.height;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
context?.drawImage(image, 0, 0, newWidth, newHeight);
const compressedBase64 = canvas.toDataURL('image/jpeg', quality);
resolve(compressedBase64);
};
image.onerror = (error) => {
reject(error);
};
});
}
}