fixed compress image
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import CloseIcon from "../icons/CloseIcon";
|
import CloseIcon from "../icons/CloseIcon";
|
||||||
import { MAX_SIZE_MB as MAX_PHOTO_SIZE_MB } from "../../hooks/useImageUpload";
|
import { MAX_SOURCE_SIZE_MB as MAX_PHOTO_SIZE_MB } from "../../hooks/useImageUpload";
|
||||||
|
|
||||||
// ─── Input field component ───────────────────────────────────────────────────
|
// ─── Input field component ───────────────────────────────────────────────────
|
||||||
function InputField({ label, error, ...props }) {
|
function InputField({ label, error, ...props }) {
|
||||||
|
|||||||
@@ -3,7 +3,11 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { compressImage } from "../utils/compressImage";
|
import { compressImage } from "../utils/compressImage";
|
||||||
import { getImageUrl } from "../config/authConstants";
|
import { getImageUrl } from "../config/authConstants";
|
||||||
|
|
||||||
|
// Лимит бэкенда на один файл — его должен выдерживать уже сжатый файл
|
||||||
export const MAX_SIZE_MB = 10;
|
export const MAX_SIZE_MB = 10;
|
||||||
|
// Лимит на исходное фото: оно всё равно сжимается перед отправкой, поэтому
|
||||||
|
// можно больше, чем MAX_SIZE_MB (фото с айфона легко весят 10+ МБ)
|
||||||
|
export const MAX_SOURCE_SIZE_MB = 30;
|
||||||
export const ACCEPT = "image/jpeg,image/png,image/webp";
|
export const ACCEPT = "image/jpeg,image/png,image/webp";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -56,15 +60,24 @@ export function useImageUpload(existingUrls = []) {
|
|||||||
setImgError(t('imageUpload.invalidType'));
|
setImgError(t('imageUpload.invalidType'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.size > MAX_SIZE_MB * 1024 * 1024) {
|
if (file.size > MAX_SOURCE_SIZE_MB * 1024 * 1024) {
|
||||||
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SIZE_MB }));
|
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SOURCE_SIZE_MB }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setCompressing(true);
|
setCompressing(true);
|
||||||
try {
|
try {
|
||||||
const compressedFiles = await Promise.all(files.map(f => compressImage(f)));
|
// По одному, а не Promise.all: декодирование нескольких 12-мегапиксельных
|
||||||
|
// фото разом может не уместиться в память на телефоне
|
||||||
|
const compressedFiles = [];
|
||||||
|
for (const f of files) {
|
||||||
|
compressedFiles.push(await compressImage(f));
|
||||||
|
}
|
||||||
|
if (compressedFiles.some(f => f.size > MAX_SIZE_MB * 1024 * 1024)) {
|
||||||
|
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SIZE_MB }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const newImages = compressedFiles.map(file => ({
|
const newImages = compressedFiles.map(file => ({
|
||||||
id: generateImageId(),
|
id: generateImageId(),
|
||||||
file,
|
file,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import RulesModal from "./RulesModal";
|
|||||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { usePostMutation } from "../hooks/usePostMutation";
|
import { usePostMutation } from "../hooks/usePostMutation";
|
||||||
import { useImageUpload, ACCEPT, MAX_SIZE_MB } from "../hooks/useImageUpload";
|
import { useImageUpload, ACCEPT, MAX_SOURCE_SIZE_MB } from "../hooks/useImageUpload";
|
||||||
import { validatePostForm } from "../utils/validatePostForm";
|
import { validatePostForm } from "../utils/validatePostForm";
|
||||||
import { formatPhone } from "../utils/formatPhone";
|
import { formatPhone } from "../utils/formatPhone";
|
||||||
import MapModal from "./MapModal";
|
import MapModal from "./MapModal";
|
||||||
@@ -242,7 +242,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
|||||||
</label>
|
</label>
|
||||||
|
|
||||||
{imgError && <p className="f-err-msg">{imgError}</p>}
|
{imgError && <p className="f-err-msg">{imgError}</p>}
|
||||||
<p className="f-hint">{t('post.photoHint', { maxSize: MAX_SIZE_MB })}</p>
|
<p className="f-hint">{t('post.photoHint', { maxSize: MAX_SOURCE_SIZE_MB })}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -151,11 +151,13 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
|||||||
alt={ad.title}
|
alt={ad.title}
|
||||||
className="f-card-img-slide"
|
className="f-card-img-slide"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<img src={getImageUrl(images[0])} alt={ad.title} />
|
<img src={getImageUrl(images[0])} alt={ad.title} loading="lazy" decoding="async" />
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
<span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
<span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
||||||
|
|||||||
@@ -1,41 +1,107 @@
|
|||||||
export async function compressImage(file, maxW = 2048, quality = 0.9) {
|
/**
|
||||||
// если файл и так маленький и лёгкий — не трогаем вообще
|
* Сжатие фото перед загрузкой: уменьшает большую сторону до maxSide и
|
||||||
if (file.size < 300 * 1024) return file;
|
* перекодирует в WebP (или JPEG, если браузер не умеет кодировать WebP).
|
||||||
|
*
|
||||||
|
* Зачем так: фото с айфона весят 5–10 МБ и имеют ~4000px по стороне, а в
|
||||||
|
* ленте показываются максимум на ~600px. Safari до сих пор не кодирует WebP
|
||||||
|
* через canvas.toBlob и молча отдаёт PNG — поэтому формат результата
|
||||||
|
* проверяем и при необходимости откатываемся на JPEG.
|
||||||
|
*/
|
||||||
|
|
||||||
const bitmap = await createImageBitmap(file, {
|
const MAX_SIDE = 1920;
|
||||||
resizeWidth: undefined, // посчитаем сами
|
const QUALITY = 0.82;
|
||||||
});
|
// Маленькие файлы с небольшим разрешением не трогаем — выигрыша не будет
|
||||||
|
const SKIP_BELOW_BYTES = 300 * 1024;
|
||||||
|
|
||||||
const scale = Math.min(1, maxW / bitmap.width);
|
/** Декодирует файл в то, что можно нарисовать на canvas, с учётом EXIF-поворота. */
|
||||||
if (scale === 1) return file; // не увеличиваем и не пересжимаем без причины
|
async function decode(file) {
|
||||||
|
if (typeof createImageBitmap === "function") {
|
||||||
|
try {
|
||||||
|
const bitmap = await createImageBitmap(file);
|
||||||
|
return { source: bitmap, width: bitmap.width, height: bitmap.height, release: () => bitmap.close?.() };
|
||||||
|
} catch {
|
||||||
|
// Safari на очень больших фото или старые браузеры — пробуем через <img>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ресайз через createImageBitmap с высоким качеством ресемплинга
|
const url = URL.createObjectURL(file);
|
||||||
const targetW = Math.round(bitmap.width * scale);
|
try {
|
||||||
const targetH = Math.round(bitmap.height * scale);
|
const img = await new Promise((resolve, reject) => {
|
||||||
const resized = await createImageBitmap(bitmap, {
|
const el = new Image();
|
||||||
resizeWidth: targetW,
|
el.onload = () => resolve(el);
|
||||||
resizeHeight: targetH,
|
el.onerror = () => reject(new Error("Не удалось прочитать изображение"));
|
||||||
resizeQuality: "high",
|
el.src = url;
|
||||||
});
|
});
|
||||||
|
return { source: img, width: img.naturalWidth, height: img.naturalHeight, release: () => {} };
|
||||||
|
} finally {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBlob(canvas, type, quality) {
|
||||||
|
return new Promise(resolve => canvas.toBlob(resolve, type, quality));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Рисует изображение в canvas нужного размера. Сильное уменьшение — в несколько шагов, так чётче. */
|
||||||
|
function drawScaled(source, srcW, srcH, targetW, targetH) {
|
||||||
|
let current = source;
|
||||||
|
let w = srcW;
|
||||||
|
let h = srcH;
|
||||||
|
|
||||||
|
while (w / 2 >= targetW && h / 2 >= targetH) {
|
||||||
|
w = Math.round(w / 2);
|
||||||
|
h = Math.round(h / 2);
|
||||||
|
const step = document.createElement("canvas");
|
||||||
|
step.width = w;
|
||||||
|
step.height = h;
|
||||||
|
const ctx = step.getContext("2d");
|
||||||
|
ctx.imageSmoothingQuality = "high";
|
||||||
|
ctx.drawImage(current, 0, 0, w, h);
|
||||||
|
current = step;
|
||||||
|
}
|
||||||
|
|
||||||
const canvas = document.createElement("canvas");
|
const canvas = document.createElement("canvas");
|
||||||
canvas.width = targetW;
|
canvas.width = targetW;
|
||||||
canvas.height = targetH;
|
canvas.height = targetH;
|
||||||
const ctx = canvas.getContext("2d");
|
const ctx = canvas.getContext("2d");
|
||||||
|
// Белый фон: у JPEG нет прозрачности, иначе прозрачные области станут чёрными
|
||||||
|
ctx.fillStyle = "#fff";
|
||||||
|
ctx.fillRect(0, 0, targetW, targetH);
|
||||||
ctx.imageSmoothingEnabled = true;
|
ctx.imageSmoothingEnabled = true;
|
||||||
ctx.imageSmoothingQuality = "high";
|
ctx.imageSmoothingQuality = "high";
|
||||||
ctx.drawImage(resized, 0, 0);
|
ctx.drawImage(current, 0, 0, targetW, targetH);
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
/**
|
||||||
canvas.toBlob(
|
* @param {File} file
|
||||||
blob => {
|
* @param {{ maxSide?: number, quality?: number }} [opts]
|
||||||
if (!blob) return reject(new Error("canvas.toBlob вернул null"));
|
* @returns {Promise<File>} сжатый файл или исходный, если сжимать не нужно/невыгодно
|
||||||
// используем WebP, если формат исходно не требовал прозрачности/точности
|
*/
|
||||||
const outName = file.name.replace(/\.[^.]+$/, "") + ".webp";
|
export async function compressImage(file, { maxSide = MAX_SIDE, quality = QUALITY } = {}) {
|
||||||
resolve(new File([blob], outName, { type: "image/webp" }));
|
const image = await decode(file);
|
||||||
},
|
try {
|
||||||
"image/webp",
|
const { width, height } = image;
|
||||||
quality
|
const scale = Math.min(1, maxSide / Math.max(width, height));
|
||||||
);
|
if (scale === 1 && file.size <= SKIP_BELOW_BYTES) return file;
|
||||||
});
|
|
||||||
}
|
const targetW = Math.max(1, Math.round(width * scale));
|
||||||
|
const targetH = Math.max(1, Math.round(height * scale));
|
||||||
|
const canvas = drawScaled(image.source, width, height, targetW, targetH);
|
||||||
|
|
||||||
|
let blob = await toBlob(canvas, "image/webp", quality);
|
||||||
|
if (!blob || blob.type !== "image/webp") {
|
||||||
|
blob = await toBlob(canvas, "image/jpeg", quality);
|
||||||
|
}
|
||||||
|
if (!blob) throw new Error("Не удалось сжать изображение");
|
||||||
|
|
||||||
|
// Размер не уменьшили и уменьшать не требовалось — оставляем оригинал
|
||||||
|
if (scale === 1 && blob.size >= file.size) return file;
|
||||||
|
|
||||||
|
const ext = blob.type === "image/webp" ? ".webp" : ".jpg";
|
||||||
|
const name = (file.name || "photo").replace(/\.[^.]+$/, "") + ext;
|
||||||
|
return new File([blob], name, { type: blob.type });
|
||||||
|
} finally {
|
||||||
|
image.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user