Resize image using JS and upload to Cloudinary

The following code grabs an image in-browser, resizes it, then uploads it to Cloudinary (CDN). It makes use of HTML's Canvas element. Basically, it creates a Canvas, draws the image into it, then exports the data as a DataURL string that contains the image. The DataURL string is then uploaded to Cloudinary via an HTTP POST call. On a successful call, Cloudinary returns a secure URL (https) of the uploaded asset.

const CLOUDINARY_URL = ''; async function resizeAndUploadImage(imageElement) { // Create a canvas element to resize the image const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // Set the canvas dimensions to the desired size canvas.width = 200; canvas.height = 200; // Draw the image onto the canvas, resizing it ctx.drawImage(imageElement, 0, 0, canvas.width, canvas.height); // Convert the canvas to a data URL const dataURL = canvas.toDataURL(); // Send the image to Cloudinary const response = await fetch(CLOUDINARY_URL, { body: JSON.stringify({ file: dataURL, upload_preset: CLOUDINARY_UPLOAD_PRESET, }), headers: { 'Content-Type': 'application/json', }, method: 'POST', }); const result = await response.json(); // Return the uploaded image's URL return result.secure_url; }