Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions packages/vips/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Bug Fixes

- Keep indexed (palette) PNGs indexed when resizing, compressing, converting, or rotating them, instead of re-encoding them as truecolour, which made sub-sizes several times larger than the original. The image quality setting is not applied to the resulting palette, since PNG output stays lossless. Reported against core as https://core.trac.wordpress.org/ticket/65922 ([#81895](https://github.com/WordPress/gutenberg/issues/81895)).

### Internal

- Enforce NodeNext module resolution in the build project so future declaration imports are checked against the package's published ESM resolution rules. ([#82088](https://github.com/WordPress/gutenberg/pull/82088))
Expand All @@ -22,16 +26,16 @@

### Breaking Changes

- `resizeImage`, `compressImage`, and `convertImageFormat` now accept their optional parameters (`quality`, `interlaced`, `smartCrop`, `stripMeta`, `maxBitdepth`) as a single trailing `options` object instead of positional arguments ([#80328](https://github.com/WordPress/gutenberg/issues/80328)).
- `resizeImage`, `compressImage`, and `convertImageFormat` now accept their optional parameters (`quality`, `interlaced`, `smartCrop`, `stripMeta`, `maxBitdepth`) as a single trailing `options` object instead of positional arguments ([#80328](https://github.com/WordPress/gutenberg/issues/80328)).

### Enhancements

- Add optional `stripMeta` and `maxBitdepth` options to `resizeImage`, `compressImage`, and `convertImageFormat`, so callers can keep all image metadata and cap the output bit depth, mirroring WordPress core's `image_strip_meta` and `image_max_bit_depth` filters ([#80216](https://github.com/WordPress/gutenberg/issues/80216)).
- Add optional `stripMeta` and `maxBitdepth` options to `resizeImage`, `compressImage`, and `convertImageFormat`, so callers can keep all image metadata and cap the output bit depth, mirroring WordPress core's `image_strip_meta` and `image_max_bit_depth` filters ([#80216](https://github.com/WordPress/gutenberg/issues/80216)).

### Bug Fixes

- `convertImageFormat`: Only decode all animation frames when the output format supports animation. Converting a long animated GIF to a still format (e.g. a JPEG poster) previously decoded every frame as one vertical strip, which exceeded the JPEG encoder's 65,500 px dimension limit and produced a film-strip image instead of a single frame ([#80259](https://github.com/WordPress/gutenberg/issues/80259)).
- `resizeImage`: Generate sub-sizes of animated images from the first frame only, matching WordPress core's server-side behavior. Re-encoding a full animated GIF per sub-size took tens of seconds per size for long GIFs and could produce sub-sizes larger than the original file ([#80266](https://github.com/WordPress/gutenberg/issues/80266)).
- `convertImageFormat`: Only decode all animation frames when the output format supports animation. Converting a long animated GIF to a still format (e.g. a JPEG poster) previously decoded every frame as one vertical strip, which exceeded the JPEG encoder's 65,500 px dimension limit and produced a film-strip image instead of a single frame ([#80259](https://github.com/WordPress/gutenberg/issues/80259)).
- `resizeImage`: Generate sub-sizes of animated images from the first frame only, matching WordPress core's server-side behavior. Re-encoding a full animated GIF per sub-size took tens of seconds per size for long GIFs and could produce sub-sizes larger than the original file ([#80266](https://github.com/WordPress/gutenberg/issues/80266)).

## 2.4.0 (2026-07-14)

Expand Down
93 changes: 76 additions & 17 deletions packages/vips/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,15 @@ export async function convertImageFormat(
saveOptions.interlace = interlaced;
}

// Keep indexed sources indexed. libvips decodes a palette image into
// RGB(A) pixels, so without this a compressed or converted PNG is
// written as truecolour and can grow several times larger than the
// indexed original.
// See https://core.trac.wordpress.org/ticket/65922.
if ( 'image/png' === outputType && isPaletteImage( image ) ) {
saveOptions.palette = true;
}

// See https://github.com/swissspidy/media-experiments/issues/324.
if ( 'image/avif' === outputType ) {
saveOptions.effort = 2;
Expand Down Expand Up @@ -397,6 +406,25 @@ function applyResizeAndCrop<
return result;
}

/**
* Determines whether a decoded image came from an indexed (palette) source.
*
* libvips decodes indexed images into full RGB(A) pixels and flags the source
* encoding with a `palette` metadata field. Writing such an image back out
* without asking for quantisation produces a truecolour PNG, which for
* palette-based artwork is typically several times larger than the indexed
* original. See https://core.trac.wordpress.org/ticket/65922.
*
* libvips only attaches the field when the source was indexed, so its presence
* is the signal. `getTypeof` reports the GType of a field, or 0 when absent.
*
* @param image Decoded vips image.
* @return Whether the source image used a palette.
*/
function isPaletteImage( image: Vips.Image ): boolean {
return image.getTypeof( 'palette' ) !== 0;
}

/**
* Reads the source bit depth of a decoded HEIF/AVIF image.
*
Expand All @@ -408,9 +436,7 @@ function applyResizeAndCrop<
* @param image Decoded vips image.
* @return Source bit depth (typically 8, 10, or 12).
*/
function getSourceBitdepth< T extends { getInt: ( name: string ) => number } >(
image: T
): number {
function getSourceBitdepth( image: Vips.Image ): number {
try {
const bitdepth = image.getInt( 'heif-bitdepth' );
if ( bitdepth > 8 ) {
Expand Down Expand Up @@ -448,19 +474,30 @@ function resolveSaveBitdepth(
/**
* Builds save options for writing an image to a buffer.
*
* @param type Output mime type.
* @param quality Desired quality (0-1).
* @param bitdepth Save bit depth; values above 8 are preserved for AVIF.
* @param stripMeta Whether to strip metadata (except color profiles),
* from the `image_strip_meta` filter.
* @param options Save option inputs.
* @param options.type Output mime type.
* @param options.quality Desired quality (0-1).
* @param options.bitdepth Save bit depth; values above 8 are preserved for
* AVIF.
* @param options.stripMeta Whether to strip metadata (except color
* profiles), from the `image_strip_meta` filter.
* @param options.isPalette Whether the source image was indexed (palette)
* encoded.
* @return Save options object.
*/
function buildSaveOptions(
type: string,
quality: number,
function buildSaveOptions( {
type,
quality,
bitdepth = 8,
stripMeta = true
): SaveOptions< typeof type > {
stripMeta = true,
isPalette = false,
}: {
type: string;
quality: number;
bitdepth?: number;
stripMeta?: boolean;
isPalette?: boolean;
} ): SaveOptions< string > {
const saveOptions: SaveOptions< typeof type > = {
// Strip metadata except ICC color profiles or gainmaps,
// matching WordPress core's behavior. The `image_strip_meta`
Expand All @@ -472,6 +509,14 @@ function buildSaveOptions(
saveOptions.Q = quality * 100;
}

// Keep indexed sources indexed. libvips decodes a palette PNG into RGB(A)
// pixels, so without this the sub-sizes are written as truecolour and can
// end up larger than the indexed original.
// See https://core.trac.wordpress.org/ticket/65922.
if ( 'image/png' === type && isPalette ) {
saveOptions.palette = true;
}

// See https://github.com/swissspidy/media-experiments/issues/324.
if ( 'image/avif' === type ) {
saveOptions.effort = 2;
Expand Down Expand Up @@ -650,12 +695,13 @@ export async function resizeImage(
}
);

const saveOptions = buildSaveOptions(
const saveOptions = buildSaveOptions( {
type,
quality,
saveBitdepth,
stripMeta
);
bitdepth: saveBitdepth,
stripMeta,
isPalette: isPaletteImage( sourceImage ),
} );
const outBuffer = image.writeToBuffer( `.${ ext }`, saveOptions );

const result = {
Expand Down Expand Up @@ -788,6 +834,10 @@ export async function rotateImage(
}
};

// Read this off the source, before the transforms below replace
// `image` with their result.
const isPalette = isPaletteImage( image );

// Apply transformation based on EXIF orientation.
// See: https://exiftool.org/TagNames/EXIF.html#:~:text=0x0112,Orientation
switch ( orientation ) {
Expand Down Expand Up @@ -834,6 +884,15 @@ export async function rotateImage(
image.remove( 'orientation' );

const saveOptions: SaveOptions< typeof type > = {};

// Keep indexed sources indexed, as the resize and convert paths do.
// Rotating writes the full-size file, so losing the palette here
// inflates the image the user actually uploaded.
// See https://github.com/WordPress/gutenberg/issues/81895.
if ( 'image/png' === type && isPalette ) {
saveOptions.palette = true;
}

const outBuffer = image.writeToBuffer( `.${ ext }`, saveOptions );

const result = {
Expand Down
143 changes: 119 additions & 24 deletions packages/vips/src/test/convert-image-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,58 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type VipsFactory from 'wasm-vips';
import { convertImageFormat, compressImage } from '../';

const { MockVipsImage, mockNewFromBuffer } = vi.hoisted( () => {
const writeToBufferMock = vi.fn( () => ( {
buffer: '',
} ) );

class ImageMock {
width = 100;
height = 100;
pageHeight = 100;
writeToBuffer = writeToBufferMock;
getInt = vi.fn( () => 0 );
}

const newFromBufferMock = vi.fn( () => new ImageMock() );

class VipsImageMock {
static newFromBuffer = newFromBufferMock;
}

return {
MockVipsImage: VipsImageMock,
mockNewFromBuffer: newFromBufferMock,
};
} );
const { MockVipsImage, mockNewFromBuffer, mockState, mockWriteToBuffer } =
vi.hoisted( () => {
/*
* Controls whether the mocked source image reports the `palette` metadata
* field, which libvips attaches only for indexed sources.
*/
const state = { hasPalette: false };

// GType of `gint`. Only whether `getTypeof` returns non-zero matters here.
const G_TYPE_INT = 24;

const writeToBufferMock = vi.fn( () => ( {
buffer: '',
} ) );

class ImageMock {
width = 100;
height = 100;
pageHeight = 100;
writeToBuffer = writeToBufferMock;
/*
* Mirrors libvips: reading a field the image does not carry throws
* rather than returning a falsy default. The production helpers rely
* on that, so the mock has to throw too or their fallbacks would
* never be exercised.
*/
getInt = vi.fn( ( name: string ) => {
throw new Error( `${ name }: no such field` );
} );
/*
* libvips only attaches `palette` when the source was indexed, so
* presence is the signal. Absent fields report GType 0 rather than
* throwing.
*/
getTypeof = vi.fn( ( name: string ) =>
'palette' === name && state.hasPalette ? G_TYPE_INT : 0
);
}

const newFromBufferMock = vi.fn( () => new ImageMock() );

class VipsImageMock {
static newFromBuffer = newFromBufferMock;
}

return {
MockVipsImage: VipsImageMock,
mockNewFromBuffer: newFromBufferMock,
mockState: state,
mockWriteToBuffer: writeToBufferMock,
};
} );

vi.mock( import( 'wasm-vips' ), () => ( {
default: vi.fn( () => ( {
Expand All @@ -39,6 +67,7 @@ vi.mock( import( 'wasm-vips' ), () => ( {
describe( 'convertImageFormat', () => {
afterEach( () => {
vi.clearAllMocks();
mockState.hasPalette = false;
} );

it( 'loads only the first frame when converting a GIF to JPEG', async () => {
Expand Down Expand Up @@ -104,4 +133,70 @@ describe( 'convertImageFormat', () => {

expect( mockNewFromBuffer ).toHaveBeenCalledWith( buffer, '', {} );
} );

describe( 'indexed (palette) PNG', () => {
/*
* Regression tests for https://core.trac.wordpress.org/ticket/65922.
* libvips decodes an indexed PNG into RGB(A) pixels, so pngsave has to
* be told to quantise back down. Otherwise compressing or converting
* to PNG rewrites the image as truecolour and inflates it.
*/
it( 'quantises a compressed indexed PNG back to a palette', async () => {
mockState.hasPalette = true;
const pngFile = new File( [ '<BLOB>' ], 'example.png', {
type: 'image/png',
} );
const buffer = await pngFile.arrayBuffer();

await compressImage( 'itemId', buffer, 'image/png' );

expect( mockWriteToBuffer ).toHaveBeenCalledWith(
'.png',
expect.objectContaining( { palette: true } )
);
// `Q` is pngsave's quantisation quality and only applies once
// `palette` is on, so the lossy image quality must not leak in.
expect( mockWriteToBuffer ).toHaveBeenCalledWith(
'.png',
expect.not.objectContaining( { Q: expect.anything() } )
);
} );

it( 'leaves a truecolour PNG unquantised', async () => {
// libvips attaches `palette` only for an indexed source, so a
// truecolour PNG carries no such field.
mockState.hasPalette = false;
const pngFile = new File( [ '<BLOB>' ], 'example.png', {
type: 'image/png',
} );
const buffer = await pngFile.arrayBuffer();

await compressImage( 'itemId', buffer, 'image/png' );

expect( mockWriteToBuffer ).toHaveBeenCalledWith(
'.png',
expect.not.objectContaining( { palette: expect.anything() } )
);
} );

it( 'does not quantise when converting an indexed source away from PNG', async () => {
mockState.hasPalette = true;
const pngFile = new File( [ '<BLOB>' ], 'example.png', {
type: 'image/png',
} );
const buffer = await pngFile.arrayBuffer();

await convertImageFormat(
'itemId',
buffer,
'image/png',
'image/webp'
);

expect( mockWriteToBuffer ).toHaveBeenCalledWith(
'.webp',
expect.not.objectContaining( { palette: expect.anything() } )
);
} );
} );
} );
Loading
Loading