From 2aca9802f566839c19ec09976a6068f2e53963dd Mon Sep 17 00:00:00 2001 From: Izhan Ali Date: Sun, 6 Sep 2026 20:55:10 +0530 Subject: [PATCH 1/2] fix(compress-png): compress without changing dimensions --- public/locales/en/image.json | 20 +- .../png/compress-png/compress-png.e2e.spec.ts | 56 ++ .../compress-png/compress-png.service.test.ts | 128 ++++ .../tools/image/png/compress-png/index.tsx | 165 +++-- .../tools/image/png/compress-png/meta.ts | 2 +- .../tools/image/png/compress-png/service.ts | 645 ++++++++++++++++++ .../tools/image/png/compress-png/test.png | Bin 0 -> 44502 bytes .../tools/image/png/compress-png/types.ts | 17 + 8 files changed, 977 insertions(+), 56 deletions(-) create mode 100644 src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts create mode 100644 src/pages/tools/image/png/compress-png/compress-png.service.test.ts create mode 100644 src/pages/tools/image/png/compress-png/test.png create mode 100644 src/pages/tools/image/png/compress-png/types.ts diff --git a/public/locales/en/image.json b/public/locales/en/image.json index c887a62e..80d8ec63 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -41,8 +41,26 @@ "title": "Compress Images" }, "compressPng": { - "description": "This is a program that compresses PNG pictures. As soon as you paste your PNG picture in the input area, the program will compress it and show the result in the output area. In the options, you can adjust the compression level, as well as find the old and new picture file sizes.", + "alreadyOptimized": "This PNG is already smaller than anything we can produce, so it was left untouched.", + "colors": "Colors in the palette", + "compressedSize": "Compressed size", + "compressing": "Compressing PNG...", + "compressionOptions": "Compression options", + "description": "This is a program that compresses PNG pictures without ever resizing them. As soon as you paste your PNG picture in the input area, the program reduces its color palette and re-encodes it, so the output keeps the exact width and height of the input. In the options, you can adjust the compression level, ask for a maximum output size, and find the old and new picture file sizes.", + "dimensions": "Dimensions", + "dimensionsUnchanged": "(unchanged)", + "dithering": "Dithering", + "ditheringDescription": "Spread the color error over neighboring pixels to hide banding in gradients, at the cost of a bigger file", + "failed": "The PNG could not be compressed. Please try again.", + "fileSizes": "File sizes", + "inputTitle": "Input PNG", + "maxOutputSizeDescription": "Maximum output size in kilobytes. The palette is shrunk until the PNG fits. Use 0 for no limit", + "noStatsYet": "Upload a PNG to see how much was saved", + "originalSize": "Original size", + "qualityDescription": "Quality percentage (1-100) — lower values keep fewer colors and give a smaller file", + "resultTitle": "Compressed PNG", "shortDescription": "Quickly compress a PNG", + "targetNotReached": "The maximum output size could not be reached, even with the smallest palette. The picture was compressed as much as possible.", "title": "Compress png" }, "convertJgpToPng": { diff --git a/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts b/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts new file mode 100644 index 00000000..84db7229 --- /dev/null +++ b/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts @@ -0,0 +1,56 @@ +import { expect, test } from '@playwright/test'; +import { Buffer } from 'buffer'; +import fs from 'fs'; +import path from 'path'; +import Jimp from 'jimp'; + +const imagePath = path.join(__dirname, 'test.png'); + +async function download(page: import('@playwright/test').Page) { + const downloadPromise = page.waitForEvent('download'); + await page.getByText('Download').click(); + const stream = await (await downloadPromise).createReadStream(); + + const chunks: Buffer[] = []; + for await (const chunk of stream) chunks.push(chunk as Buffer); + return Buffer.concat(chunks); +} + +test.describe('Compress PNG tool', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/png/compress-png'); + await page.locator('input[type="file"]').setInputFiles(imagePath); + await expect(page.getByText('Colors in the palette')).toBeVisible(); + }); + + test('should compress without touching the dimensions', async ({ page }) => { + const original = await Jimp.read(fs.readFileSync(imagePath)); + const compressed = await download(page); + + const image = await Jimp.read(compressed); + expect(image.bitmap.width).toBe(original.bitmap.width); + expect(image.bitmap.height).toBe(original.bitmap.height); + expect(compressed.length).toBeLessThan(fs.statSync(imagePath).size); + }); + + test('should honor the maximum output size', async ({ page }) => { + await page.locator('input[name="maxOutputSizeInKB"]').fill('5'); + + // Wait for the run that honors the new budget to land. + await expect + .poll(async () => { + const stats = await page.getByText(/Compressed size:/).innerText(); + const size = stats.match(/([\d.]+) KB/); + return size ? parseFloat(size[1]) : Infinity; + }) + .toBeLessThanOrEqual(5); + + const original = await Jimp.read(fs.readFileSync(imagePath)); + const compressed = await download(page); + + expect(compressed.length).toBeLessThanOrEqual(5 * 1024); + const image = await Jimp.read(compressed); + expect(image.bitmap.width).toBe(original.bitmap.width); + expect(image.bitmap.height).toBe(original.bitmap.height); + }); +}); diff --git a/src/pages/tools/image/png/compress-png/compress-png.service.test.ts b/src/pages/tools/image/png/compress-png/compress-png.service.test.ts new file mode 100644 index 00000000..be963d43 --- /dev/null +++ b/src/pages/tools/image/png/compress-png/compress-png.service.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest'; +import Jimp from 'jimp'; +import { compressPngPixels } from './service'; +import { InitialValuesType } from './types'; + +const WIDTH = 120; +const HEIGHT = 90; + +const defaultOptions: InitialValuesType = { + quality: 60, + dithering: false, + maxOutputSizeInKB: 0 +}; + +/** A noisy gradient: enough distinct colors that a palette actually helps. */ +function gradient(): Uint8ClampedArray { + const pixels = new Uint8ClampedArray(WIDTH * HEIGHT * 4); + for (let y = 0; y < HEIGHT; y++) { + for (let x = 0; x < WIDTH; x++) { + const p = (y * WIDTH + x) * 4; + pixels[p] = (x * 255) / WIDTH; + pixels[p + 1] = (y * 255) / HEIGHT; + pixels[p + 2] = (x * y) % 256; + pixels[p + 3] = 255; + } + } + return pixels; +} + +async function readBack(data: Uint8Array) { + return Jimp.read(Buffer.from(data)); +} + +describe('compressPngPixels', () => { + it('keeps the original dimensions', async () => { + const { data } = await compressPngPixels( + gradient(), + WIDTH, + HEIGHT, + defaultOptions + ); + + const image = await readBack(data); + expect(image.bitmap.width).toBe(WIDTH); + expect(image.bitmap.height).toBe(HEIGHT); + }); + + it('produces a smaller file than the raw pixels', async () => { + const pixels = gradient(); + const { data } = await compressPngPixels( + pixels, + WIDTH, + HEIGHT, + defaultOptions + ); + + expect(data.length).toBeLessThan(pixels.length); + }); + + it('keeps colors close to the original ones', async () => { + const { data } = await compressPngPixels(gradient(), WIDTH, HEIGHT, { + ...defaultOptions, + quality: 100 + }); + + const image = await readBack(data); + const original = gradient(); + let worstDelta = 0; + for (let y = 0; y < HEIGHT; y += 7) { + for (let x = 0; x < WIDTH; x += 7) { + const p = (y * WIDTH + x) * 4; + const { r, g, b } = Jimp.intToRGBA(image.getPixelColor(x, y)); + worstDelta = Math.max( + worstDelta, + Math.abs(r - original[p]), + Math.abs(g - original[p + 1]), + Math.abs(b - original[p + 2]) + ); + } + } + + expect(worstDelta).toBeLessThan(40); + }); + + it('lowers the palette until the size budget is met', async () => { + const budgetInKB = 3; + const result = await compressPngPixels(gradient(), WIDTH, HEIGHT, { + ...defaultOptions, + quality: 100, + maxOutputSizeInKB: budgetInKB + }); + + expect(result.targetReached).toBe(true); + expect(result.data.length).toBeLessThanOrEqual(budgetInKB * 1024); + expect(result.colors).toBeLessThan(256); + }); + + it('preserves fully transparent pixels', async () => { + const pixels = gradient(); + for (let i = 3; i < pixels.length; i += 4) { + if (i < (pixels.length / 4) * 2) pixels[i] = 0; + } + + const { data } = await compressPngPixels( + pixels, + WIDTH, + HEIGHT, + defaultOptions + ); + + const image = await readBack(data); + expect(Jimp.intToRGBA(image.getPixelColor(0, 0)).a).toBe(0); + expect(Jimp.intToRGBA(image.getPixelColor(WIDTH - 1, HEIGHT - 1)).a).toBe( + 255 + ); + }); + + it('supports palettes below 8 bits per pixel', async () => { + const result = await compressPngPixels(gradient(), WIDTH, HEIGHT, { + ...defaultOptions, + quality: 1 + }); + + const image = await readBack(result.data); + expect(image.bitmap.width).toBe(WIDTH); + expect(result.colors).toBeLessThanOrEqual(3); + }); +}); diff --git a/src/pages/tools/image/png/compress-png/index.tsx b/src/pages/tools/image/png/compress-png/index.tsx index a4e7bcc5..85a18fc9 100644 --- a/src/pages/tools/image/png/compress-png/index.tsx +++ b/src/pages/tools/image/png/compress-png/index.tsx @@ -1,56 +1,58 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; -import * as Yup from 'yup'; +import React, { useContext, useRef, useState } from 'react'; +import { Box, Typography } from '@mui/material'; +import { useTranslation } from 'react-i18next'; +import ToolContent from '@components/ToolContent'; import ToolImageInput from '@components/input/ToolImageInput'; import ToolFileResult from '@components/result/ToolFileResult'; -import TextFieldWithDesc from 'components/options/TextFieldWithDesc'; -import imageCompression from 'browser-image-compression'; -import Typography from '@mui/material/Typography'; -import ToolContent from '@components/ToolContent'; +import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { ToolComponentProps } from '@tools/defineTool'; +import { updateNumberField } from '@utils/string'; +import { CustomSnackBarContext } from '../../../../../contexts/CustomSnackBarContext'; +import { compressPng, CompressPngResult } from './service'; +import { InitialValuesType } from './types'; -const initialValues = { - rate: '50' +const initialValues: InitialValuesType = { + quality: 60, + dithering: false, + maxOutputSizeInKB: 0 }; -const validationSchema = Yup.object({ - // splitSeparator: Yup.string().required('The separator is required') -}); -export default function ChangeColorsInPng({ title }: ToolComponentProps) { +export default function CompressPng({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); const [input, setInput] = useState(null); - const [result, setResult] = useState(null); - const [originalSize, setOriginalSize] = useState(null); // Store original file size - const [compressedSize, setCompressedSize] = useState(null); // Store compressed file size + const [result, setResult] = useState(null); + const [isProcessing, setIsProcessing] = useState(false); + const { showSnackBar } = useContext(CustomSnackBarContext); + // Options change while a compression is running; only the last one counts. + const latestRun = useRef(0); - const compressImage = async (file: File, rate: number) => { - if (!file) return; + const compute = async (values: InitialValuesType, input: File | null) => { + if (!input) { + setResult(null); + return; + } - // Set original file size - setOriginalSize(file.size); - - const options = { - maxSizeMB: 1, // Maximum size in MB - maxWidthOrHeight: 1024, // Maximum width or height - quality: rate / 100, // Convert percentage to decimal (e.g., 50% becomes 0.5) - useWebWorker: true - }; + const run = ++latestRun.current; + setIsProcessing(true); try { - const compressedFile = await imageCompression(file, options); - setResult(compressedFile); - setCompressedSize(compressedFile.size); // Set compressed file size + const compressed = await compressPng(input, values); + if (run !== latestRun.current) return; + + setResult(compressed); } catch (error) { - console.error('Error during compression:', error); + if (run !== latestRun.current) return; + setResult(null); + showSnackBar( + error instanceof Error ? error.message : t('compressPng.failed'), + 'error' + ); + } finally { + if (run === latestRun.current) setIsProcessing(false); } }; - const compute = (optionsValues: typeof initialValues, input: any) => { - if (!input) return; - - const { rate } = optionsValues; - compressImage(input, Number(rate)); // Pass the rate as a number - }; - return ( } resultComponent={ } initialValues={initialValues} getGroups={({ values, updateField }) => [ { - title: 'Compression options', + title: t('compressPng.compressionOptions'), component: ( updateField('rate', val)} - description={'Compression rate (1-100)'} + name="quality" + type="number" + inputProps={{ min: 1, max: 100, step: 1 }} + value={values.quality} + onOwnChange={(value) => + updateNumberField(value, 'quality', updateField) + } + description={t('compressPng.qualityDescription')} + /> + + updateNumberField(value, 'maxOutputSizeInKB', updateField) + } + description={t('compressPng.maxOutputSizeDescription')} + /> + updateField('dithering', value)} + description={t('compressPng.ditheringDescription')} /> ) }, { - title: 'File sizes', + title: t('compressPng.fileSizes'), component: ( - - {originalSize !== null && ( + {result ? ( + - Original Size: {(originalSize / 1024).toFixed(2)} KB + {t('compressPng.originalSize')}:{' '} + {formatSize(result.originalSize)} - )} - {compressedSize !== null && ( - Compressed Size: {(compressedSize / 1024).toFixed(2)} KB + {t('compressPng.compressedSize')}:{' '} + {formatSize(result.compressedSize)} ( + {savings(result.originalSize, result.compressedSize)}) - )} - + + {t('compressPng.dimensions')}: {result.width} ×{' '} + {result.height} {t('compressPng.dimensionsUnchanged')} + + + {t('compressPng.colors')}: {result.colors} + + {result.keptOriginal && ( + + {t('compressPng.alreadyOptimized')} + + )} + {!result.targetReached && ( + + {t('compressPng.targetNotReached')} + + )} + + ) : ( + + {t('compressPng.noStatsYet')} + + )} ) } @@ -109,3 +156,13 @@ export default function ChangeColorsInPng({ title }: ToolComponentProps) { /> ); } + +function formatSize(bytes: number): string { + return `${(bytes / 1024).toFixed(2)} KB`; +} + +function savings(originalSize: number, compressedSize: number): string { + if (!originalSize) return '0%'; + const saved = ((originalSize - compressedSize) / originalSize) * 100; + return `${saved >= 0 ? '-' : '+'}${Math.abs(saved).toFixed(1)}%`; +} diff --git a/src/pages/tools/image/png/compress-png/meta.ts b/src/pages/tools/image/png/compress-png/meta.ts index 224d20e4..c5302f4d 100644 --- a/src/pages/tools/image/png/compress-png/meta.ts +++ b/src/pages/tools/image/png/compress-png/meta.ts @@ -12,6 +12,6 @@ export const tool = defineTool('png', { path: 'compress-png', icon: 'material-symbols-light:compress', - keywords: ['compress', 'png'], + keywords: ['compress', 'png', 'optimize', 'quantize', 'reduce', 'size'], component: lazy(() => import('./index')) }); diff --git a/src/pages/tools/image/png/compress-png/service.ts b/src/pages/tools/image/png/compress-png/service.ts index e69de29b..d8345e57 100644 --- a/src/pages/tools/image/png/compress-png/service.ts +++ b/src/pages/tools/image/png/compress-png/service.ts @@ -0,0 +1,645 @@ +import { InitialValuesType } from './types'; + +export interface CompressPngResult { + file: File; + originalSize: number; + compressedSize: number; + /** Width of the output, always identical to the width of the input. */ + width: number; + /** Height of the output, always identical to the height of the input. */ + height: number; + /** Number of colors kept in the output palette. */ + colors: number; + /** False when the size budget could not be met even with a 2 color palette. */ + targetReached: boolean; + /** True when the input was already smaller than anything we could produce. */ + keptOriginal: boolean; +} + +const MAX_PALETTE_SIZE = 256; + +/** + * Compresses a PNG by reducing its color palette, never its dimensions. + * + * The picture is decoded at its native size, quantized to a palette and + * re-encoded as an indexed PNG, which is where the size savings come from. + * Width and height are carried over untouched. + */ +export async function compressPng( + file: File, + options: InitialValuesType +): Promise { + const { data, width, height } = await decodeImage(file); + const compressed = await compressPngPixels(data, width, height, options); + + // An already optimized PNG can be smaller than our best attempt. Handing + // back a heavier file would be worse than doing nothing at all. + const keptOriginal = compressed.data.length >= file.size; + const targetBytes = Math.max(0, Math.round(options.maxOutputSizeInKB * 1024)); + + return { + file: keptOriginal + ? file + : new File([new Uint8Array(compressed.data)], file.name, { + type: 'image/png' + }), + originalSize: file.size, + compressedSize: keptOriginal ? file.size : compressed.data.length, + width, + height, + colors: compressed.colors, + targetReached: keptOriginal + ? !targetBytes || file.size <= targetBytes + : compressed.targetReached, + keptOriginal + }; +} + +/** + * Palette-compresses raw RGBA pixels into a PNG byte stream. The pixels are + * read and normalized in place. Exposed separately from {@link compressPng} + * so it can run without a DOM. + */ +export async function compressPngPixels( + pixels: Uint8ClampedArray, + width: number, + height: number, + options: InitialValuesType +): Promise<{ data: Uint8Array; colors: number; targetReached: boolean }> { + if (width <= 0 || height <= 0) { + throw new Error('The picture has no pixels to compress'); + } + + // Fully transparent pixels can hold any RGB value. Flattening them to a + // single color removes noise the palette would otherwise waste entries on. + for (let i = 0; i < pixels.length; i += 4) { + if (pixels[i + 3] === 0) { + pixels[i] = 0; + pixels[i + 1] = 0; + pixels[i + 2] = 0; + } + } + + const histogram = buildHistogram(pixels); + const targetBytes = Math.max(0, Math.round(options.maxOutputSizeInKB * 1024)); + + let output: { data: Uint8Array; colors: number } | null = null; + for (const paletteSize of paletteSizes(options.quality, targetBytes)) { + const palette = buildPalette(histogram, paletteSize); + const indices = mapToPalette(pixels, width, height, palette, { + dithering: options.dithering + }); + output = { + data: await encodeIndexedPng(indices, width, height, palette), + colors: palette.size + }; + if (!targetBytes || output.data.length <= targetBytes) break; + } + + if (!output) throw new Error('The picture could not be compressed'); + + return { + ...output, + targetReached: !targetBytes || output.data.length <= targetBytes + }; +} + +/** + * Palette sizes to try, largest first. Without a size budget the quality + * setting alone decides; with one, we keep halving the palette until the + * output fits. + */ +function paletteSizes(quality: number, targetBytes: number): number[] { + const clamped = Math.min(100, Math.max(1, Math.round(quality || 0))); + const requested = Math.max(2, Math.round((clamped / 100) * MAX_PALETTE_SIZE)); + + if (!targetBytes) return [requested]; + + const fallbacks = [128, 64, 32, 16, 8, 4, 2].filter((n) => n < requested); + return [requested, ...fallbacks]; +} + +/* -------------------------------------------------------------------------- */ +/* Decoding */ +/* -------------------------------------------------------------------------- */ + +async function decodeImage(file: File): Promise { + const source = await loadImageSource(file); + const canvas = document.createElement('canvas'); + canvas.width = source.width; + canvas.height = source.height; + + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (!ctx) throw new Error('Canvas is not supported in this browser'); + + ctx.drawImage(source.image, 0, 0); + if (typeof ImageBitmap !== 'undefined' && source.image instanceof ImageBitmap) + source.image.close(); + + return ctx.getImageData(0, 0, canvas.width, canvas.height); +} + +async function loadImageSource( + file: File +): Promise<{ image: CanvasImageSource; width: number; height: number }> { + if (typeof createImageBitmap === 'function') { + const bitmap = await createImageBitmap(file); + return { image: bitmap, width: bitmap.width, height: bitmap.height }; + } + + const url = URL.createObjectURL(file); + try { + const image = await new Promise((resolve, reject) => { + const element = new Image(); + element.onload = () => resolve(element); + element.onerror = () => reject(new Error('The PNG could not be read')); + element.src = url; + }); + return { + image, + width: image.naturalWidth, + height: image.naturalHeight + }; + } finally { + URL.revokeObjectURL(url); + } +} + +/* -------------------------------------------------------------------------- */ +/* Color quantization */ +/* -------------------------------------------------------------------------- */ + +/** + * Population of the picture bucketed by color. Channels are bucketed on 6 bits + * to keep the map small, while the exact channel sums are kept so palette + * entries stay accurate. + */ +interface Histogram { + count: number[]; + rSum: number[]; + gSum: number[]; + bSum: number[]; + aSum: number[]; +} + +interface Palette { + size: number; + r: Uint8Array; + g: Uint8Array; + b: Uint8Array; + a: Uint8Array; + /** Number of leading entries that are not fully opaque. */ + transparentEntries: number; +} + +function buildHistogram(pixels: Uint8ClampedArray): Histogram { + const buckets = new Map(); + const histogram: Histogram = { + count: [], + rSum: [], + gSum: [], + bSum: [], + aSum: [] + }; + + for (let i = 0; i < pixels.length; i += 4) { + const r = pixels[i]; + const g = pixels[i + 1]; + const b = pixels[i + 2]; + const a = pixels[i + 3]; + const key = + ((r >> 2) << 18) | ((g >> 2) << 12) | ((b >> 2) << 6) | (a >> 2); + + let bucket = buckets.get(key); + if (bucket === undefined) { + bucket = histogram.count.length; + buckets.set(key, bucket); + histogram.count.push(0); + histogram.rSum.push(0); + histogram.gSum.push(0); + histogram.bSum.push(0); + histogram.aSum.push(0); + } + + histogram.count[bucket]++; + histogram.rSum[bucket] += r; + histogram.gSum[bucket] += g; + histogram.bSum[bucket] += b; + histogram.aSum[bucket] += a; + } + + return histogram; +} + +interface Box { + members: number[]; + count: number; + axis: number; + range: number; + priority: number; +} + +/** Median cut over the histogram, weighted by how common each color is. */ +function buildPalette(histogram: Histogram, maxColors: number): Palette { + const bucketCount = histogram.count.length; + const centers = new Float32Array(bucketCount * 4); + for (let i = 0; i < bucketCount; i++) { + const count = histogram.count[i]; + centers[i * 4] = histogram.rSum[i] / count; + centers[i * 4 + 1] = histogram.gSum[i] / count; + centers[i * 4 + 2] = histogram.bSum[i] / count; + centers[i * 4 + 3] = histogram.aSum[i] / count; + } + + const allMembers = Array.from({ length: bucketCount }, (_, i) => i); + const boxes = [makeBox(allMembers, histogram, centers)]; + + while (boxes.length < maxColors) { + let target = -1; + for (let i = 0; i < boxes.length; i++) { + if (boxes[i].range <= 0) continue; + if (target === -1 || boxes[i].priority > boxes[target].priority) + target = i; + } + if (target === -1) break; + + const [first, second] = splitBox(boxes[target], histogram, centers); + boxes.splice(target, 1, first, second); + } + + return paletteFromBoxes(boxes, histogram); +} + +function makeBox( + members: number[], + histogram: Histogram, + centers: Float32Array +): Box { + const min = [255, 255, 255, 255]; + const max = [0, 0, 0, 0]; + let count = 0; + + for (const member of members) { + count += histogram.count[member]; + for (let channel = 0; channel < 4; channel++) { + const value = centers[member * 4 + channel]; + if (value < min[channel]) min[channel] = value; + if (value > max[channel]) max[channel] = value; + } + } + + let axis = 0; + let range = 0; + for (let channel = 0; channel < 4; channel++) { + const channelRange = max[channel] - min[channel]; + if (channelRange > range) { + range = channelRange; + axis = channel; + } + } + + return { + members, + count, + axis, + range, + // Volume times population: splits the box that hurts the picture most. + priority: range * count + }; +} + +function splitBox( + box: Box, + histogram: Histogram, + centers: Float32Array +): [Box, Box] { + const sorted = [...box.members].sort( + (left, right) => + centers[left * 4 + box.axis] - centers[right * 4 + box.axis] + ); + + // Cut where half of the pixels of the box lie, so both halves matter equally. + const half = box.count / 2; + let accumulated = 0; + let splitAt = 0; + for (let i = 0; i < sorted.length - 1; i++) { + accumulated += histogram.count[sorted[i]]; + splitAt = i + 1; + if (accumulated >= half) break; + } + + return [ + makeBox(sorted.slice(0, splitAt), histogram, centers), + makeBox(sorted.slice(splitAt), histogram, centers) + ]; +} + +/** + * Averages every box into one palette entry, then orders the palette so the + * see-through entries come first — that keeps the tRNS chunk as short as + * possible. + */ +function paletteFromBoxes(boxes: Box[], histogram: Histogram): Palette { + const entries = boxes + .filter((box) => box.count > 0) + .map((box) => { + let count = 0; + let r = 0; + let g = 0; + let b = 0; + let a = 0; + for (const member of box.members) { + count += histogram.count[member]; + r += histogram.rSum[member]; + g += histogram.gSum[member]; + b += histogram.bSum[member]; + a += histogram.aSum[member]; + } + return { + r: Math.round(r / count), + g: Math.round(g / count), + b: Math.round(b / count), + a: Math.round(a / count) + }; + }); + + entries.sort( + (left, right) => + Number(left.a === 255) - Number(right.a === 255) || left.a - right.a + ); + + const size = Math.max(1, entries.length); + const palette: Palette = { + size, + r: new Uint8Array(size), + g: new Uint8Array(size), + b: new Uint8Array(size), + a: new Uint8Array(size), + transparentEntries: entries.filter((entry) => entry.a !== 255).length + }; + + entries.forEach((entry, index) => { + palette.r[index] = entry.r; + palette.g[index] = entry.g; + palette.b[index] = entry.b; + palette.a[index] = entry.a; + }); + + return palette; +} + +/* -------------------------------------------------------------------------- */ +/* Palette mapping */ +/* -------------------------------------------------------------------------- */ + +function mapToPalette( + pixels: Uint8ClampedArray, + width: number, + height: number, + palette: Palette, + { dithering }: { dithering: boolean } +): Uint8Array { + const indices = new Uint8Array(width * height); + // Cache of nearest matches, keyed on the color rounded to 5/5/5/4 bits. + const cache = new Int16Array(1 << 19).fill(-1); + + const nearest = (r: number, g: number, b: number, a: number): number => { + const key = ((r >> 3) << 14) | ((g >> 3) << 9) | ((b >> 3) << 4) | (a >> 4); + const cached = cache[key]; + if (cached >= 0) return cached; + + let best = 0; + let bestDistance = Infinity; + for (let i = 0; i < palette.size; i++) { + const dr = r - palette.r[i]; + const dg = g - palette.g[i]; + const db = b - palette.b[i]; + const da = a - palette.a[i]; + // Alpha is weighted up: a wrong opacity is more visible than a wrong hue. + const distance = dr * dr + dg * dg + db * db + 3 * da * da; + if (distance < bestDistance) { + bestDistance = distance; + best = i; + } + } + + cache[key] = best; + return best; + }; + + if (!dithering) { + for (let i = 0; i < indices.length; i++) { + const p = i * 4; + indices[i] = nearest( + pixels[p], + pixels[p + 1], + pixels[p + 2], + pixels[p + 3] + ); + } + return indices; + } + + // Floyd-Steinberg: the error of each pixel is pushed onto its neighbors. + // Rows are padded by one pixel on each side so the x-1 spill needs no bounds + // check. + let currentRow = new Float32Array((width + 2) * 4); + let nextRow = new Float32Array((width + 2) * 4); + const errors = new Float32Array(4); + + for (let y = 0; y < height; y++) { + nextRow.fill(0); + + for (let x = 0; x < width; x++) { + const p = (y * width + x) * 4; + const e = (x + 1) * 4; + + const r = clampChannel(pixels[p] + currentRow[e]); + const g = clampChannel(pixels[p + 1] + currentRow[e + 1]); + const b = clampChannel(pixels[p + 2] + currentRow[e + 2]); + const a = clampChannel(pixels[p + 3] + currentRow[e + 3]); + + const index = nearest(r, g, b, a); + indices[y * width + x] = index; + + errors[0] = r - palette.r[index]; + errors[1] = g - palette.g[index]; + errors[2] = b - palette.b[index]; + errors[3] = a - palette.a[index]; + + for (let channel = 0; channel < 4; channel++) { + const error = errors[channel]; + if (error === 0) continue; + currentRow[e + 4 + channel] += (error * 7) / 16; + nextRow[e - 4 + channel] += (error * 3) / 16; + nextRow[e + channel] += (error * 5) / 16; + nextRow[e + 4 + channel] += error / 16; + } + } + + const done = currentRow; + currentRow = nextRow; + nextRow = done; + } + + return indices; +} + +function clampChannel(value: number): number { + if (value <= 0) return 0; + if (value >= 255) return 255; + return Math.round(value); +} + +/* -------------------------------------------------------------------------- */ +/* PNG encoding */ +/* -------------------------------------------------------------------------- */ + +const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + +async function encodeIndexedPng( + indices: Uint8Array, + width: number, + height: number, + palette: Palette +): Promise { + const bitDepth = paletteBitDepth(palette.size); + const idat = await deflate(scanlines(indices, width, height, bitDepth)); + + const ihdr = new Uint8Array(13); + const header = new DataView(ihdr.buffer); + header.setUint32(0, width); + header.setUint32(4, height); + ihdr[8] = bitDepth; + ihdr[9] = 3; // color type 3: indexed + ihdr[10] = 0; // deflate + ihdr[11] = 0; // adaptive filtering + ihdr[12] = 0; // no interlacing + + const plte = new Uint8Array(palette.size * 3); + for (let i = 0; i < palette.size; i++) { + plte[i * 3] = palette.r[i]; + plte[i * 3 + 1] = palette.g[i]; + plte[i * 3 + 2] = palette.b[i]; + } + + const chunks = [PNG_SIGNATURE, chunk('IHDR', ihdr), chunk('PLTE', plte)]; + if (palette.transparentEntries > 0) { + chunks.push(chunk('tRNS', palette.a.slice(0, palette.transparentEntries))); + } + chunks.push(chunk('IDAT', idat), chunk('IEND', new Uint8Array(0))); + + return concat(chunks); +} + +function paletteBitDepth(colors: number): 1 | 2 | 4 | 8 { + if (colors <= 2) return 1; + if (colors <= 4) return 2; + if (colors <= 16) return 4; + return 8; +} + +/** Packs the indices into PNG scanlines, each prefixed by its filter byte. */ +function scanlines( + indices: Uint8Array, + width: number, + height: number, + bitDepth: number +): Uint8Array { + const bytesPerRow = Math.ceil((width * bitDepth) / 8); + const raw = new Uint8Array((bytesPerRow + 1) * height); + const perByte = 8 / bitDepth; + + for (let y = 0; y < height; y++) { + const rowStart = y * (bytesPerRow + 1); + raw[rowStart] = 0; // filter 0: indexed data does not gain from filtering + + if (bitDepth === 8) { + raw.set(indices.subarray(y * width, (y + 1) * width), rowStart + 1); + continue; + } + + for (let x = 0; x < width; x++) { + const shift = 8 - bitDepth * ((x % perByte) + 1); + raw[rowStart + 1 + Math.floor(x / perByte)] |= + indices[y * width + x] << shift; + } + } + + return raw; +} + +function chunk(type: string, data: Uint8Array): Uint8Array { + const out = new Uint8Array(data.length + 12); + const view = new DataView(out.buffer); + view.setUint32(0, data.length); + for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i); + out.set(data, 8); + view.setUint32(data.length + 8, crc32(out.subarray(4, data.length + 8))); + return out; +} + +let crcTable: Uint32Array | null = null; + +function crc32(bytes: Uint8Array): number { + if (!crcTable) { + crcTable = new Uint32Array(256); + for (let i = 0; i < 256; i++) { + let value = i; + for (let bit = 0; bit < 8; bit++) { + value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1; + } + crcTable[i] = value >>> 0; + } + } + + let crc = 0xffffffff; + for (let i = 0; i < bytes.length; i++) { + crc = crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ 0xffffffff) >>> 0; +} + +type CompressionStreamConstructor = new ( + format: 'deflate' +) => TransformStream; + +/** Deflates into the zlib container PNG expects for its IDAT payload. */ +async function deflate(bytes: Uint8Array): Promise { + const CompressionStreamImpl = ( + globalThis as unknown as { + CompressionStream?: CompressionStreamConstructor; + } + ).CompressionStream; + + if (!CompressionStreamImpl) { + throw new Error('This browser cannot compress PNG data'); + } + + const { readable, writable } = new CompressionStreamImpl('deflate'); + const writer = writable.getWriter(); + // Not awaited: the writer only drains once we start reading below. + const written = writer.write(bytes).then(() => writer.close()); + + const reader = readable.getReader(); + const chunks: Uint8Array[] = []; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (value) chunks.push(value); + } + await written; + + return concat(chunks); +} + +function concat(parts: Uint8Array[]): Uint8Array { + const total = parts.reduce((size, part) => size + part.length, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; +} diff --git a/src/pages/tools/image/png/compress-png/test.png b/src/pages/tools/image/png/compress-png/test.png new file mode 100644 index 0000000000000000000000000000000000000000..b87ff70bab16aa295d09651e5506212b061e9f12 GI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JFSm-TK!c12Me^-zju1$!o;fKs{8iuhT-Nb!x*rUOHCpj4UjbwK0Xb4Bf%@SFj zwBqPtq%AvR@rZEZ&xu|O*Hw{oLoSuP8{FRtf{pJ!!>BNR=l=ng1pP~59rLdM0000< KMNUMnLSTYdE2_Q# literal 0 HcmV?d00001 diff --git a/src/pages/tools/image/png/compress-png/types.ts b/src/pages/tools/image/png/compress-png/types.ts new file mode 100644 index 00000000..513d9c79 --- /dev/null +++ b/src/pages/tools/image/png/compress-png/types.ts @@ -0,0 +1,17 @@ +export interface InitialValuesType { + /** + * 1-100. Drives the size of the color palette the picture is reduced to: + * 100 keeps 256 colors, lower values keep fewer colors and compress harder. + */ + quality: number; + /** + * Spread the quantization error over neighboring pixels (Floyd-Steinberg). + * Hides banding in gradients at the cost of a slightly bigger file. + */ + dithering: boolean; + /** + * Optional size budget in kilobytes. When set, the palette is shrunk + * step by step until the output fits. 0 disables the budget. + */ + maxOutputSizeInKB: number; +} From 1fe23b43d237c367e63e07f5e0cfc94bd5fb05f3 Mon Sep 17 00:00:00 2001 From: Izhan Ali Date: Tue, 6 Oct 2026 02:16:58 +0530 Subject: [PATCH 2/2] add: support for multiple PNG compression and zip downloading --- public/locales/en/image.json | 11 +- .../png/compress-png/compress-png.e2e.spec.ts | 28 +++ .../tools/image/png/compress-png/index.tsx | 163 +++++++++++++----- .../tools/image/png/compress-png/service.ts | 45 +++++ 4 files changed, 199 insertions(+), 48 deletions(-) diff --git a/public/locales/en/image.json b/public/locales/en/image.json index 80d8ec63..a91e29b8 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -42,25 +42,28 @@ }, "compressPng": { "alreadyOptimized": "This PNG is already smaller than anything we can produce, so it was left untouched.", + "alreadyOptimizedFiles": "Already smaller than anything we can produce, left untouched: {{files}}", "colors": "Colors in the palette", "compressedSize": "Compressed size", "compressing": "Compressing PNG...", "compressionOptions": "Compression options", - "description": "This is a program that compresses PNG pictures without ever resizing them. As soon as you paste your PNG picture in the input area, the program reduces its color palette and re-encodes it, so the output keeps the exact width and height of the input. In the options, you can adjust the compression level, ask for a maximum output size, and find the old and new picture file sizes.", + "description": "This is a program that compresses one or more PNG pictures without ever resizing them. As soon as you add your PNG pictures in the input area, the program reduces their color palette and re-encodes them, so each output keeps the exact width and height of the input. In the options, you can adjust the compression level, ask for a maximum output size, and find the old and new picture file sizes.", "dimensions": "Dimensions", "dimensionsUnchanged": "(unchanged)", "dithering": "Dithering", "ditheringDescription": "Spread the color error over neighboring pixels to hide banding in gradients, at the cost of a bigger file", "failed": "The PNG could not be compressed. Please try again.", "fileSizes": "File sizes", - "inputTitle": "Input PNG", + "inputTitle": "Input PNGs", "maxOutputSizeDescription": "Maximum output size in kilobytes. The palette is shrunk until the PNG fits. Use 0 for no limit", - "noStatsYet": "Upload a PNG to see how much was saved", + "noStatsYet": "Upload PNGs to see how much was saved", "originalSize": "Original size", "qualityDescription": "Quality percentage (1-100) — lower values keep fewer colors and give a smaller file", - "resultTitle": "Compressed PNG", + "resultTitle": "Compressed PNGs", "shortDescription": "Quickly compress a PNG", + "someFailed": "These files could not be compressed: {{files}}", "targetNotReached": "The maximum output size could not be reached, even with the smallest palette. The picture was compressed as much as possible.", + "targetNotReachedFiles": "The maximum output size could not be reached for: {{files}}. They were compressed as much as possible.", "title": "Compress png" }, "convertJgpToPng": { diff --git a/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts b/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts index 84db7229..652fe13c 100644 --- a/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts +++ b/src/pages/tools/image/png/compress-png/compress-png.e2e.spec.ts @@ -3,6 +3,7 @@ import { Buffer } from 'buffer'; import fs from 'fs'; import path from 'path'; import Jimp from 'jimp'; +import JSZip from 'jszip'; const imagePath = path.join(__dirname, 'test.png'); @@ -54,3 +55,30 @@ test.describe('Compress PNG tool', () => { expect(image.bitmap.height).toBe(original.bitmap.height); }); }); + +test.describe('Compress PNG tool with several files', () => { + test('should zip every compressed file', async ({ page }) => { + const buffer = fs.readFileSync(imagePath); + await page.goto('/png/compress-png'); + await page.locator('input[type="file"]').setInputFiles([ + { name: 'first.png', mimeType: 'image/png', buffer }, + { name: 'second.png', mimeType: 'image/png', buffer } + ]); + + const downloadPromise = page.waitForEvent('download'); + await page.getByText('Download All as ZIP').click(); + const stream = await (await downloadPromise).createReadStream(); + const chunks: Buffer[] = []; + for await (const chunk of stream) chunks.push(chunk as Buffer); + + const zip = await JSZip.loadAsync(Buffer.concat(chunks)); + expect(Object.keys(zip.files).sort()).toEqual(['first.png', 'second.png']); + + const original = await Jimp.read(buffer); + for (const name of ['first.png', 'second.png']) { + const image = await Jimp.read(await zip.file(name)!.async('nodebuffer')); + expect(image.bitmap.width).toBe(original.bitmap.width); + expect(image.bitmap.height).toBe(original.bitmap.height); + } + }); +}); diff --git a/src/pages/tools/image/png/compress-png/index.tsx b/src/pages/tools/image/png/compress-png/index.tsx index 85a18fc9..10cd414b 100644 --- a/src/pages/tools/image/png/compress-png/index.tsx +++ b/src/pages/tools/image/png/compress-png/index.tsx @@ -2,14 +2,17 @@ import React, { useContext, useRef, useState } from 'react'; import { Box, Typography } from '@mui/material'; import { useTranslation } from 'react-i18next'; import ToolContent from '@components/ToolContent'; -import ToolImageInput from '@components/input/ToolImageInput'; +import ToolMultipleImageInput, { + MultiImageInput +} from '@components/input/ToolMultipleImageInput'; import ToolFileResult from '@components/result/ToolFileResult'; +import ToolMultiFileResult from '@components/result/ToolMultiFileResult'; import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { ToolComponentProps } from '@tools/defineTool'; import { updateNumberField } from '@utils/string'; import { CustomSnackBarContext } from '../../../../../contexts/CustomSnackBarContext'; -import { compressPng, CompressPngResult } from './service'; +import { compressPngs, CompressPngResult, CompressPngsResult } from './service'; import { InitialValuesType } from './types'; const initialValues: InitialValuesType = { @@ -20,15 +23,18 @@ const initialValues: InitialValuesType = { export default function CompressPng({ title }: ToolComponentProps) { const { t } = useTranslation('image'); - const [input, setInput] = useState(null); - const [result, setResult] = useState(null); + const [input, setInput] = useState([]); + const [result, setResult] = useState(null); const [isProcessing, setIsProcessing] = useState(false); const { showSnackBar } = useContext(CustomSnackBarContext); // Options change while a compression is running; only the last one counts. const latestRun = useRef(0); - const compute = async (values: InitialValuesType, input: File | null) => { - if (!input) { + const compute = async ( + values: InitialValuesType, + input: MultiImageInput[] + ) => { + if (input.length === 0) { setResult(null); return; } @@ -37,10 +43,19 @@ export default function CompressPng({ title }: ToolComponentProps) { setIsProcessing(true); try { - const compressed = await compressPng(input, values); + const compressed = await compressPngs( + input.map((image) => image.file), + values + ); if (run !== latestRun.current) return; setResult(compressed); + if (compressed.failed.length > 0) { + showSnackBar( + t('compressPng.someFailed', { files: compressed.failed.join(', ') }), + 'error' + ); + } } catch (error) { if (run !== latestRun.current) return; setResult(null); @@ -58,7 +73,8 @@ export default function CompressPng({ title }: ToolComponentProps) { title={title} input={input} inputComponent={ - } resultComponent={ - + result?.zipFile ? ( + item.file)} + zipFile={result.zipFile} + loading={isProcessing} + loadingText={t('compressPng.compressing')} + /> + ) : ( + + ) } initialValues={initialValues} getGroups={({ values, updateField }) => [ @@ -113,35 +139,8 @@ export default function CompressPng({ title }: ToolComponentProps) { title: t('compressPng.fileSizes'), component: ( - {result ? ( - - - {t('compressPng.originalSize')}:{' '} - {formatSize(result.originalSize)} - - - {t('compressPng.compressedSize')}:{' '} - {formatSize(result.compressedSize)} ( - {savings(result.originalSize, result.compressedSize)}) - - - {t('compressPng.dimensions')}: {result.width} ×{' '} - {result.height} {t('compressPng.dimensionsUnchanged')} - - - {t('compressPng.colors')}: {result.colors} - - {result.keptOriginal && ( - - {t('compressPng.alreadyOptimized')} - - )} - {!result.targetReached && ( - - {t('compressPng.targetNotReached')} - - )} - + {result && result.results.length > 0 ? ( + ) : ( {t('compressPng.noStatsYet')} @@ -157,6 +156,82 @@ export default function CompressPng({ title }: ToolComponentProps) { ); } +function FileStats({ results }: { results: CompressPngResult[] }) { + const { t } = useTranslation('image'); + + if (results.length === 1) { + const [result] = results; + return ( + + + {t('compressPng.originalSize')}: {formatSize(result.originalSize)} + + + {t('compressPng.compressedSize')}: {formatSize(result.compressedSize)}{' '} + ({savings(result.originalSize, result.compressedSize)}) + + + {t('compressPng.dimensions')}: {result.width} × {result.height}{' '} + {t('compressPng.dimensionsUnchanged')} + + + {t('compressPng.colors')}: {result.colors} + + {result.keptOriginal && ( + + {t('compressPng.alreadyOptimized')} + + )} + {!result.targetReached && ( + + {t('compressPng.targetNotReached')} + + )} + + ); + } + + const originalTotal = results.reduce((sum, r) => sum + r.originalSize, 0); + const compressedTotal = results.reduce((sum, r) => sum + r.compressedSize, 0); + const keptOriginal = results.filter((r) => r.keptOriginal); + const targetMissed = results.filter((r) => !r.targetReached); + + return ( + + + {t('compressPng.originalSize')}: {formatSize(originalTotal)} + + + {t('compressPng.compressedSize')}: {formatSize(compressedTotal)} ( + {savings(originalTotal, compressedTotal)}) + + + {results.map((result, index) => ( + + {result.file.name}: {formatSize(result.originalSize)} →{' '} + {formatSize(result.compressedSize)} ( + {savings(result.originalSize, result.compressedSize)}) + + ))} + + {keptOriginal.length > 0 && ( + + {t('compressPng.alreadyOptimizedFiles', { + files: keptOriginal.map((r) => r.file.name).join(', ') + })} + + )} + {targetMissed.length > 0 && ( + + {t('compressPng.targetNotReachedFiles', { + files: targetMissed.map((r) => r.file.name).join(', ') + })} + + )} + + ); +} + function formatSize(bytes: number): string { return `${(bytes / 1024).toFixed(2)} KB`; } diff --git a/src/pages/tools/image/png/compress-png/service.ts b/src/pages/tools/image/png/compress-png/service.ts index d8345e57..35606ab3 100644 --- a/src/pages/tools/image/png/compress-png/service.ts +++ b/src/pages/tools/image/png/compress-png/service.ts @@ -1,3 +1,4 @@ +import JSZip from 'jszip'; import { InitialValuesType } from './types'; export interface CompressPngResult { @@ -16,8 +17,52 @@ export interface CompressPngResult { keptOriginal: boolean; } +export interface CompressPngsResult { + results: CompressPngResult[]; + /** Zip of every compressed file, only set when there is more than one. */ + zipFile: File | null; + /** Names of the files that could not be compressed. */ + failed: string[]; +} + const MAX_PALETTE_SIZE = 256; +/** Compresses several PNGs one after the other and zips them when needed. */ +export async function compressPngs( + files: File[], + options: InitialValuesType +): Promise { + const results: CompressPngResult[] = []; + const failed: string[] = []; + let firstError: unknown = null; + + // One at a time: each picture is decoded at full size, so running them in + // parallel would multiply memory use. + for (const file of files) { + try { + results.push(await compressPng(file, options)); + } catch (error) { + console.error(`Error compressing ${file.name}:`, error); + failed.push(file.name); + firstError ??= error; + } + } + + if (results.length === 0 && firstError) throw firstError; + + let zipFile: File | null = null; + if (results.length > 1) { + const zip = new JSZip(); + results.forEach(({ file }) => zip.file(file.name, file)); + const zipBlob = await zip.generateAsync({ type: 'blob' }); + zipFile = new File([zipBlob], 'compressed-pngs.zip', { + type: 'application/zip' + }); + } + + return { results, zipFile, failed }; +} + /** * Compresses a PNG by reducing its color palette, never its dimensions. *