function downloadImage(imageUrl, filename) { fetch(imageUrl) .then(response => { if (!response.ok) { throw new Error('Network response was not ok.'); } return response.blob(); }) .then(blob => { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; // Set the desired filename document.body.appendChild(a); // Append to body to make it clickable a.click(); // Programmatically click the link document.body.removeChild(a); // Remove the link after clicking URL.revokeObjectURL(url); // Clean up the object URL }) .catch(error => { console.error('Error downloading image:', error); alert('Could not download image. It might be due to cross-origin restrictions or network issues.'); }); } // Example usage (you can trigger this with a jQuery click event) // $('#downloadButton').on('click', function() { // downloadImage('https://example.com/path/to/image.jpg', 'my_custom_image.jpg'); // });