diff --git a/docs/changelog.md b/docs/changelog.md index 3ad1b31a..a4835faf 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -52,6 +52,9 @@ Requires libvips v8.13.0 Emit warnings when previous calls in the same pipeline will be ignored. [#3319](https://github.com/lovell/sharp/issues/3319) +* Ensure PNG bitdepth can be set for non-palette output. + [#3322](https://github.com/lovell/sharp/issues/3322) + * Ensure resized image is unpremultiplied before composite. [#3334](https://github.com/lovell/sharp/issues/3334) diff --git a/lib/output.js b/lib/output.js index dcdfbb02..338c9a04 100644 --- a/lib/output.js +++ b/lib/output.js @@ -407,6 +407,14 @@ function png (options) { if (is.defined(options.adaptiveFiltering)) { this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); } + const colours = options.colours || options.colors; + if (is.defined(colours)) { + if (is.integer(colours) && is.inRange(colours, 2, 256)) { + this.options.pngBitdepth = bitdepthFromColourCount(colours); + } else { + throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); + } + } if (is.defined(options.palette)) { this._setBooleanOption('pngPalette', options.palette); } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { @@ -427,14 +435,6 @@ function png (options) { throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); } } - const colours = options.colours || options.colors; - if (is.defined(colours)) { - if (is.integer(colours) && is.inRange(colours, 2, 256)) { - this.options.pngBitdepth = bitdepthFromColourCount(colours); - } else { - throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); - } - } if (is.defined(options.dither)) { if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { this.options.pngDither = options.dither; diff --git a/test/unit/png.js b/test/unit/png.js index e996b514..b3bf4fc1 100644 --- a/test/unit/png.js +++ b/test/unit/png.js @@ -190,6 +190,23 @@ describe('PNG', function () { }); }); + it('Can set bitdepth of PNG without palette', async () => { + const data = await sharp({ + create: { + width: 8, height: 8, channels: 3, background: 'red' + } + }) + .toColourspace('b-w') + .png({ colours: 2, palette: false }) + .toBuffer(); + + const { channels, paletteBitDepth, size, space } = await sharp(data).metadata(); + assert.strictEqual(channels, 1); + assert.strictEqual(paletteBitDepth, undefined); + assert.strictEqual(size, 90); + assert.strictEqual(space, 'b-w'); + }); + it('Valid PNG libimagequant dither value produces image of same size or smaller', function () { const inputPngBuffer = fs.readFileSync(fixtures.inputPng); return Promise.all([