Extract Alpha from Image [JS1]

A JavaScript one-liner to extract the transparency mask of an image


iOS 15: Works (iOS 15.2 beta 1) iOS 15: Works (iOS 15.2 beta 1)

A single line of JavaScript to get the transparency mask (a.k.a. alpha channel) of an image. Once extracted, it can be modified and/or applied to another image. Example:

Example of mask extraction

The shortcut extracts silently the masks from any images received as input, giving them the same name/s. These masks can be directly used with the "Mask Image" action in Shortcuts.

When run without input, the shortcut works as a demo, allowing the user to select one or more files and showing the result of the conversion.

Don't download the shortcut

If you just want the code, there's no need to download the shortcut. Copy this and paste it in a "URL" action:

data:text/html,<script>with(document){let i=createElement("img");i.src="data:image/png;base64,REPLACETHISWITHBASE64IMAGE",i.onload=()=>{with(createElement("canvas")){height=i.height,width=i.width;with(getContext("2d")){drawImage(i,0,0),globalCompositeOperation="source-out",fillRect(0,0,width,height),globalCompositeOperation="destination-over",fillStyle='white',fillRect(0,0,width,height)}write(toDataURL("image/png").slice(22))}}}</script>

Replace the REPLACETHISWITHBASE64IMAGE fragment with the base64-encoded image, add a "Get File of Type" with type com.apple.webarchive below, and decode the base64 output to get the mask.

I use "Get File of Type" instead of "Get Contents of Webpage" to avoid that the user is misleading told that the shortcut uses Safari.

Latest Release Notes

1.0.0 - Nov. 8, 2021, 9:07 p.m.

First public version