Add image resizing utility and integrate it into product image upload process
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
|
||||
import {forkJoin, map, of, switchMap, Observable, catchError} from 'rxjs';
|
||||
import {forkJoin, map, of, switchMap, Observable, catchError, from} from 'rxjs';
|
||||
import {PsItem} from '../interfaces/ps-item';
|
||||
import {PsProduct} from '../interfaces/ps-product';
|
||||
import {ProductListItem} from '../interfaces/product-list-item';
|
||||
@@ -499,9 +499,20 @@ export class PrestashopService {
|
||||
}
|
||||
|
||||
uploadProductImage(productId: number, file: File) {
|
||||
// 1) Compression AVANT upload
|
||||
return from(resizeImage(file, 1600, 1600, 0.8)).pipe(
|
||||
switchMap(compressedFile => {
|
||||
const fd = new FormData();
|
||||
fd.append('image', file);
|
||||
return this.http.post(`${this.base}/images/products/${productId}`, fd);
|
||||
fd.append('image', compressedFile); // ← image compressée
|
||||
|
||||
// 2) Envoi vers ton backend (identique à avant)
|
||||
return this.http.post(
|
||||
`${this.base}/images/products/${productId}`,
|
||||
fd,
|
||||
{ reportProgress: true, observe: 'events' }
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// -------- Stock (quantité) — gestion fine via stock_availables
|
||||
|
||||
45
client/src/app/utils/image-utils.ts
Normal file
45
client/src/app/utils/image-utils.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
function resizeImage(
|
||||
file: File,
|
||||
maxWidth = 1600,
|
||||
maxHeight = 1600,
|
||||
quality = 0.8
|
||||
): Promise<File> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = e => {
|
||||
if (!e.target?.result) return reject('Cannot load file');
|
||||
|
||||
img.onload = () => {
|
||||
let { width, height } = img;
|
||||
|
||||
const ratio = Math.min(maxWidth / width, maxHeight / height, 1);
|
||||
const newW = Math.round(width * ratio);
|
||||
const newH = Math.round(height * ratio);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = newW;
|
||||
canvas.height = newH;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return reject('Cannot get canvas context');
|
||||
|
||||
ctx.drawImage(img, 0, 0, newW, newH);
|
||||
|
||||
canvas.toBlob(
|
||||
blob => {
|
||||
if (!blob) return reject('Compression failed');
|
||||
resolve(new File([blob], file.name.replace(/\.[^.]+$/, '.jpg'), { type: 'image/jpeg' }));
|
||||
},
|
||||
'image/jpeg',
|
||||
quality
|
||||
);
|
||||
};
|
||||
|
||||
img.src = e.target.result as string;
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user