Convert Image to Grayscale [JS1]

A JavaScript one-liner to convert an image to grayscale


Description

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

A single line of JavaScript to apply a "black and white" filter to images. The result can be used as is or combined with the original image to get a partially desaturated version. As the example shows, the conversion supports images with alpha channel (transparency):

Example of grayscale conversion

The shortcut converts silently any images received as input, giving them the same name/s.

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="saturation",fillRect(0,0,width,height),globalCompositeOperation="destination-in",drawImage(i,0,0)}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 decolored image.

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:08 p.m.

First public version