Merge pull request #97 from SlimusMinus/fix-compress_image
All checks were successful
deploy-frontend / deploy (push) Successful in 46s

fixed compress image
This commit is contained in:
SlimusMinus
2026-10-15 01:29:45 +03:00
committed by GitHub
5 changed files with 118 additions and 37 deletions

View File

@@ -1,6 +1,6 @@
import { useTranslation } from 'react-i18next';
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 ───────────────────────────────────────────────────
function InputField({ label, error, ...props }) {

View File

@@ -3,7 +3,11 @@ import { useTranslation } from 'react-i18next';
import { compressImage } from "../utils/compressImage";
import { getImageUrl } from "../config/authConstants";
// Лимит бэкенда на один файл — его должен выдерживать уже сжатый файл
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";
/**
@@ -56,15 +60,24 @@ export function useImageUpload(existingUrls = []) {
setImgError(t('imageUpload.invalidType'));
return;
}
if (file.size > MAX_SIZE_MB * 1024 * 1024) {
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SIZE_MB }));
if (file.size > MAX_SOURCE_SIZE_MB * 1024 * 1024) {
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SOURCE_SIZE_MB }));
return;
}
}
setCompressing(true);
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 => ({
id: generateImageId(),
file,

View File

@@ -4,7 +4,7 @@ import RulesModal from "./RulesModal";
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
import { useTranslation } from 'react-i18next';
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 { formatPhone } from "../utils/formatPhone";
import MapModal from "./MapModal";
@@ -242,7 +242,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
</label>
{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>
<button

View File

@@ -151,11 +151,13 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
alt={ad.title}
className="f-card-img-slide"
draggable={false}
loading="lazy"
decoding="async"
/>
))}
</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>

View File

@@ -1,41 +1,107 @@
export async function compressImage(file, maxW = 2048, quality = 0.9) {
// если файл и так маленький и лёгкий — не трогаем вообще
if (file.size < 300 * 1024) return file;
/**
* Сжатие фото перед загрузкой: уменьшает большую сторону до maxSide и
* перекодирует в WebP (или JPEG, если браузер не умеет кодировать WebP).
*
* Зачем так: фото с айфона весят 5–10 МБ и имеют ~4000px по стороне, а в
* ленте показываются максимум на ~600px. Safari до сих пор не кодирует WebP
* через canvas.toBlob и молча отдаёт PNG — поэтому формат результата
* проверяем и при необходимости откатываемся на JPEG.
*/
const bitmap = await createImageBitmap(file, {
resizeWidth: undefined, // посчитаем сами
});
const MAX_SIDE = 1920;
const QUALITY = 0.82;
// Маленькие файлы с небольшим разрешением не трогаем — выигрыша не будет
const SKIP_BELOW_BYTES = 300 * 1024;
const scale = Math.min(1, maxW / bitmap.width);
if (scale === 1) return file; // не увеличиваем и не пересжимаем без причины
/** Декодирует файл в то, что можно нарисовать на canvas, с учётом EXIF-поворота. */
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 targetW = Math.round(bitmap.width * scale);
const targetH = Math.round(bitmap.height * scale);
const resized = await createImageBitmap(bitmap, {
resizeWidth: targetW,
resizeHeight: targetH,
resizeQuality: "high",
});
const url = URL.createObjectURL(file);
try {
const img = await new Promise((resolve, reject) => {
const el = new Image();
el.onload = () => resolve(el);
el.onerror = () => reject(new Error("Не удалось прочитать изображение"));
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");
canvas.width = targetW;
canvas.height = targetH;
const ctx = canvas.getContext("2d");
// Белый фон: у JPEG нет прозрачности, иначе прозрачные области станут чёрными
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, targetW, targetH);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(resized, 0, 0);
ctx.drawImage(current, 0, 0, targetW, targetH);
return canvas;
}
return new Promise((resolve, reject) => {
canvas.toBlob(
blob => {
if (!blob) return reject(new Error("canvas.toBlob вернул null"));
// используем WebP, если формат исходно не требовал прозрачности/точности
const outName = file.name.replace(/\.[^.]+$/, "") + ".webp";
resolve(new File([blob], outName, { type: "image/webp" }));
},
"image/webp",
quality
);
});
}
/**
* @param {File} file
* @param {{ maxSide?: number, quality?: number }} [opts]
* @returns {Promise<File>} сжатый файл или исходный, если сжимать не нужно/невыгодно
*/
export async function compressImage(file, { maxSide = MAX_SIDE, quality = QUALITY } = {}) {
const image = await decode(file);
try {
const { width, height } = image;
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();
}
}