Skip to content

Commit 4e21189

Browse files
authored
Fix loading of grayscale images in node.js (#181)
* Ensure the image loaded by sharp.js has the correct number of channels * Do not assume default channels
1 parent 86de50d commit 4e21189

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/utils/image.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,18 @@ if (BROWSER_ENV) {
3636
// Running in Node.js, electron, or other non-browser environment
3737

3838
loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {
39+
const metadata = await img.metadata();
40+
const rawChannels = metadata.channels;
41+
3942
let { data, info } = await img.raw().toBuffer({ resolveWithObject: true });
40-
return new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);
43+
44+
const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);
45+
if (rawChannels !== undefined && rawChannels !== info.channels) {
46+
// Make sure the new image has the same number of channels as the input image.
47+
// This is necessary for grayscale images.
48+
newImage.convert(rawChannels);
49+
}
50+
return newImage;
4151
}
4252

4353
} else {

0 commit comments

Comments
 (0)