This is a solution that works for me. It is JS and PHP.
First create anchor tag with href to the image you want to download. If you want you can set custom name to the save.as file (download attribute).
Then JS function fetchImageAndDownload. And then PHP part.
This code bassicaly tricks the browser into thinking that the file(image) is located on your server, as you temporarly save the file on your server.
<a href="url to the image" download="custom_name">Download</a>
function fetchImageAndDownload (e) {
e.preventDefault();
const url = this.getAttribute("href");
const downloadName = this.download;
const img = document.createElement("img");
img.addEventListener("load", () => {
const a = document.createElement("a");
a.href = img.src;
a.download = downloadName;
a.click();
});
img.src = 'fetchImage?url='+ url;
}
fetchImage() {
$url = $_GET["url"];
$info = getimagesize($url);
header("Content-type: ". $info['mime']);
readfile($url);
die();
}