Add premultiplied boolean flag for raw pixel data input (#2685)

This commit is contained in:
Michael Nutt
2021-05-03 14:30:37 -04:00
committed by GitHub
parent 309918a878
commit 9a1e8ed574
9 changed files with 60 additions and 1 deletions

View File

@@ -90,6 +90,7 @@ module.exports = {
inputPngEmbed: getPath('embedgravitybird.png'), // Released to sharp under a CC BY 4.0
inputPngRGBWithAlpha: getPath('2569067123_aca715a2ee_o.png'), // http://www.flickr.com/photos/grizdave/2569067123/ (same as inputJpg)
inputPngImageInAlpha: getPath('image-in-alpha.png'), // https://github.com/lovell/sharp/issues/1597
inputPngSolidAlpha: getPath('with-alpha.png'), // https://github.com/lovell/sharp/issues/1599
inputWebP: getPath('4.webp'), // http://www.gstatic.com/webp/gallery/4.webp
inputWebPWithTransparency: getPath('5_webp_a.webp'), // http://www.gstatic.com/webp/gallery3/5_webp_a.webp

BIN
test/fixtures/with-alpha.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -107,6 +107,52 @@ describe('Raw pixel data', function () {
});
});
it('RGBA premultiplied', function (done) {
// Convert to raw pixel data
sharp(fixtures.inputPngSolidAlpha)
.resize(256)
.raw()
.toBuffer(function (err, data, info) {
if (err) throw err;
assert.strictEqual(256, info.width);
assert.strictEqual(192, info.height);
assert.strictEqual(4, info.channels);
const originalData = Buffer.from(data);
// Premultiply image data
for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
const norm = alpha / 255;
if (alpha < 255) {
data[i] = Math.round(data[i] * norm);
data[i + 1] = Math.round(data[i + 1] * norm);
data[i + 2] = Math.round(data[i + 2] * norm);
}
}
// Convert back to PNG
sharp(data, {
raw: {
width: info.width,
height: info.height,
channels: info.channels,
premultiplied: true
}
})
.raw()
.toBuffer(function (err, data, info) {
if (err) throw err;
assert.strictEqual(256, info.width);
assert.strictEqual(192, info.height);
assert.strictEqual(4, info.channels);
assert.equal(data.compare(originalData), 0, 'output buffer matches unpremultiplied input buffer');
done();
});
});
});
it('JPEG to raw Stream and back again', function (done) {
const width = 32;
const height = 24;