Add image resizing utility and integrate it into product image upload process

This commit is contained in:
Vincent Guillet
2025-12-03 19:46:31 +01:00
parent eb94697955
commit fd6c730ae3
2 changed files with 60 additions and 4 deletions

View File

@@ -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

View 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);
});
}