<?php
$keyword = 'nature';
?>
<script>
var image = new Image();
image.crossOrigin = "anonymous";
image.src = "https://source.unsplash.com/random/800x500/?<?=$keyword?>";
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually
var fileName = image.src.split(/(\\|\/)/g).pop();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... преобразование
blob = canvas.toDataURL("image/jpeg");
$("body").html("<div class='container mt-5'><p>Кликните по изображению, чтобы загрузить на компьютер</p><a download='<?=$_GET['file']?>' href='" + blob + "'><img class='img-fluid rounded' src='" + blob + "'/></a><form id='form' action method='post'><input id='hidden_data' type='hidden' name='hidden_data' value='" + blob + "'><div class='row g-2 mt-4'> <div class='col-md-6'><input type='submit' name='file_download' value='Привязать фото к статье' class='btn btn-outline-secondary w-100' /></div> <div class='col-md-6'><a href='#' class='btn btn-outline-secondary w-100' onclick='location.reload(); return false;'>Обновить</a></div> </div></form></div>");
};
</script>
<?php
if( isset($_POST['file_download']))
{
//upload image to server
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/img/'. $keyword .'/';
$img = $_POST['hidden_data'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . $_GET['file'] . ".jpg";
$success = file_put_contents($file, $data);
echo "<meta http-equiv='refresh' content='0; url=/$keyword/$_GET[file]'>";
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>