Skip to content

Commit

Permalink
Add function to apply mask to RawImage. (#1020)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
BritishWerewolf and xenova authored Dec 5, 2024
1 parent 2ee715c commit f8dbc89
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/utils/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,46 @@ export class RawImage {
return this._update(newData, this.width, this.height, 4);
}

/**
* Apply an alpha mask to the image. Operates in place.
* @param {RawImage} mask The mask to apply. It should have a single channel.
* @returns {RawImage} The masked image.
* @throws {Error} If the mask is not the same size as the image.
* @throws {Error} If the image does not have 4 channels.
* @throws {Error} If the mask is not a single channel.
*/
putAlpha(mask) {
if (mask.width !== this.width || mask.height !== this.height) {
throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${mask.width}x${mask.height}`);
}
if (mask.channels !== 1) {
throw new Error(`Expected mask to have 1 channel, but got ${mask.channels}`);
}

const this_data = this.data;
const mask_data = mask.data;
const num_pixels = this.width * this.height;
if (this.channels === 3) {
// Convert to RGBA and simultaneously apply mask to alpha channel
const newData = new Uint8ClampedArray(num_pixels * 4);
for (let i = 0, in_offset = 0, out_offset = 0; i < num_pixels; ++i) {
newData[out_offset++] = this_data[in_offset++];
newData[out_offset++] = this_data[in_offset++];
newData[out_offset++] = this_data[in_offset++];
newData[out_offset++] = mask_data[i];
}
return this._update(newData, this.width, this.height, 4);

} else if (this.channels === 4) {
// Apply mask to alpha channel in place
for (let i = 0; i < num_pixels; ++i) {
this_data[4 * i + 3] = mask_data[i];
}
return this;
}
throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`);
}

/**
* Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
* @param {number} width The width of the new image. `null` or `-1` will preserve the aspect ratio.
Expand Down

0 comments on commit f8dbc89

Please sign in to comment.