Skip to content

Commit f8dbc89

Browse files
Add function to apply mask to RawImage. (#1020)
* Add function to apply mask to RawImage. Add function to get a pixel and set a pixel. * Simplify to use a single loop. * Throw instead of silently converting to avoid unexpected errors. * Rename function to better reflect what it does. Remove unused functions. * Update `putAlpha` function --------- Co-authored-by: Joshua Lochner <[email protected]>
1 parent 2ee715c commit f8dbc89

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/utils/image.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,46 @@ export class RawImage {
303303
return this._update(newData, this.width, this.height, 4);
304304
}
305305

306+
/**
307+
* Apply an alpha mask to the image. Operates in place.
308+
* @param {RawImage} mask The mask to apply. It should have a single channel.
309+
* @returns {RawImage} The masked image.
310+
* @throws {Error} If the mask is not the same size as the image.
311+
* @throws {Error} If the image does not have 4 channels.
312+
* @throws {Error} If the mask is not a single channel.
313+
*/
314+
putAlpha(mask) {
315+
if (mask.width !== this.width || mask.height !== this.height) {
316+
throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${mask.width}x${mask.height}`);
317+
}
318+
if (mask.channels !== 1) {
319+
throw new Error(`Expected mask to have 1 channel, but got ${mask.channels}`);
320+
}
321+
322+
const this_data = this.data;
323+
const mask_data = mask.data;
324+
const num_pixels = this.width * this.height;
325+
if (this.channels === 3) {
326+
// Convert to RGBA and simultaneously apply mask to alpha channel
327+
const newData = new Uint8ClampedArray(num_pixels * 4);
328+
for (let i = 0, in_offset = 0, out_offset = 0; i < num_pixels; ++i) {
329+
newData[out_offset++] = this_data[in_offset++];
330+
newData[out_offset++] = this_data[in_offset++];
331+
newData[out_offset++] = this_data[in_offset++];
332+
newData[out_offset++] = mask_data[i];
333+
}
334+
return this._update(newData, this.width, this.height, 4);
335+
336+
} else if (this.channels === 4) {
337+
// Apply mask to alpha channel in place
338+
for (let i = 0; i < num_pixels; ++i) {
339+
this_data[4 * i + 3] = mask_data[i];
340+
}
341+
return this;
342+
}
343+
throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`);
344+
}
345+
306346
/**
307347
* Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
308348
* @param {number} width The width of the new image. `null` or `-1` will preserve the aspect ratio.

0 commit comments

Comments
 (0)