Photon also can be executed on Node.js via WebAssembly. In this guide, we're going to take a look at how to read, filter and save images on Node.js using Photon and the fs module.
To convert your image to a Photon-compatible image, you'll need to encode your image as base64 and then create a PhotonImage from the encoded base64:
1
2
3
4
5
6
// read file, then convert to base64varbase64=fs.readFileSync(`input.png`,{encoding:'base64'});letdata=base64.replace(/^data:image\/(png|jpg);base64,/,"");// convert base64 to PhotonImagevarphtn_img=photon.PhotonImage.new_from_base64(data);
To save and write your image, you'll need to convert the PhotonImage back to base64, this base64 can then be saved as an image.
1
2
3
4
5
6
7
// get base64 from filtered image, and write letoutput_base64=phtn_img.get_base64();letoutput_image_name="output.png";varoutput_data=output_base64.replace(/^data:image\/\w+;base64,/,'');fs.writeFile(output_image_name,output_data,{encoding:'base64'},function(err){});
varfs=require('fs');varphoton=require("@silvia-odwyer/photon-node");constfetch=require('node-fetch');global.fetch=fetch;functiongrayscaleImage(){// read file, then convert to base64varbase64=fs.readFileSync(`input.png`,{encoding:'base64'});letdata=base64.replace(/^data:image\/(png|jpg);base64,/,"");// convert base64 to PhotonImagevarphtn_img=photon.PhotonImage.new_from_base64(data);photon.grayscale(phtn_img);// get base64 from filtered image, and write letoutput_base64=phtn_img.get_base64();letoutput_image_name="output.png";varoutput_data=output_base64.replace(/^data:image\/\w+;base64,/,'');fs.writeFile(output_image_name,output_data,{encoding:'base64'},function(err){});console.log(`Saved ${output_image_name}`);}grayscaleImage();