Code of the save_cnvimg.php file Answer by Mohammed Owens This data URL string can then be sent to the server. The server will need to process this string, and save data as an image file.,This base64 string can be sent to the server where it can be processed and saved as an image file.,For example, in PHP :,Canvas images can be uploaded to server-side as a data URL string, base64 string or as a file.
The data URL of the canvas image can be retrieved using the toDataURL() method.
// PNG data url let image_data_url = document.querySelector("#canvas").toDataURL(); // JPEG data url let image_data_url = document.querySelector("#canvas").toDataURL('image/jpeg');
The base64 data of the canvas image can be retrieved by first using toDataURL() to get the data URL string, and then stripping off the starting characters from it.
// PNG base64 let image_base64 = document.querySelector("#canvas").toDataURL().replace(/^data:image\/png;base64,/, ""); // JPEG base64 let image_base64 = document.querySelector("#canvas").toDataURL('image/jpeg').replace(/^data:image\/jpeg;base64,/, "");
This base64 string can be sent to the server where it can be processed and saved as an image file.
The canvas image can be converted to a blob using toBlob() method. The blob can then be converted to a file.
// PNG file let file = null; let blob = document.querySelector("#canvas").toBlob(function(blob) < file = new File([blob], 'test.png', < type: 'image/png' >); >, 'image/png'); // JPEG file let file = null; let blob = document.querySelector("#canvas").toBlob(function(blob) < file = new File([blob], 'test.jpg', < type: 'image/jpeg' >); >, 'image/jpeg');
Answer by Lainey Peterson define(‘UPLOAD_DIR’, ‘images/’); $img = $_POST[‘img’]; //base64 string $data = file_get_contents($img); $file = UPLOAD_DIR . uniqid() . ‘.png’; $success = file_put_contents($file, $data); print $success ? $file : ‘Unable to save the file.’;,define (‘UPLOAD_DIR’, ‘imagens /’); $ img = $ _POST [‘img’]; // base64 string $ data = file_get_contents ($ img); $ arquivo = UPLOAD_DIR. uniqid (). ‘.png’; $ success = file_put_contents ($ arquivo, $ dados); print $ sucesso? $ file: ‘Não foi possível salvar o arquivo.’;,define(‘UPLOAD_DIR’, ‘uploads/’); foreach ($_REQUEST[‘image’] as $value) < $img = $value; $img = str_replace('data:image/jpeg;base64,', '', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); $data1[] = $file; >echo json_encode($data1);,define(‘UPLOAD_DIR’, ‘img/’);
$base64 = "data:image/png;base64,gAAAQ8AAAC6CAMAAACHgTh+AA="; if(preg_match("^data:image\/(?(?:png|gif|jpg|jpeg));base64,(?.+)$", $base64, $matchings)) < $imageData = base64_decode($matchings['image']); $extension = $matchings['extension']; $filename = sprintf("image.%s", $extension); if(file_put_contents($filename, $imageData)) < // image saved >>
Answer by Gustavo Glass A DOMString indicating the image format. The default type is image/png; that type is also used if the given type isn’t supported. ,The created image is in a resolution of 96dpi.,ImageBitmapRenderingContext,© 2005-2021 Mozilla and individual contributors. Content is available under these licenses.
canvas.toBlob(callback, type, quality);
Answer by Leila Petersen javascript — How to save a canvas as a PNG image? , javascript — HTML5 canvas: image resizing , javascript — How to use it canvas.toDataURL () save canvas as image? ,When the image is completed, allow users to save the canvas as an image file to the server
Which led to the JavaScript code:
function saveImage() < var canvasData = canvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST", "testSave.php", false); ajax.onreadystatechange = function() < console.log(ajax.responseText); >ajax.setRequestHeader("Content-Type", "application/upload"); ajax.send("imgData=" + canvasData); >
and corresponding PHP (testSave.php):
More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:
$data = $_POST['imgData']; $file = "/path/to/file.png"; $uri = substr($data,strpos($data, ",") + 1); file_put_contents($file, base64_decode($uri)); echo $file;
Following Salvidor Dali’s link I changed the AJAX request to be:
function saveImage() < var canvasData = canvas.toDataURL("image/png"); var xmlHttpReq = false; if (window.XMLHttpRequest) < ajax = new XMLHttpRequest(); >else if (window.ActiveXObject) < ajax = new ActiveXObject("Microsoft.XMLHTTP"); >ajax.open("POST", "testSave.php", false); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function() < console.log(ajax.responseText); >ajax.send("imgData=" + canvasData); >
Answer by Adele Morrison AWS certification career opportunities, ask related question , ask related question , How to convert entire div data into image and.
I have already created my data (template-containing image,text,label etc) inside div now i want to convert it into image format. is there any technique to convert a specific div content into images without using canvas.anybody plz help me ! i want to convert entire «mydiv» content into image and save that image into my image directory, when i click on save ?
Template Design Good Morning
Answer by Hanna Delacruz Finally the save.php, in the receiving end, treats the data (from the POST):,Going back to the top the form-structure (still in first index.php) that uses this to send/submit/(transfer image data):,From there you can use the Capturing screenshot from camera example, to get that render target as base64 to be sent with an AJAX request to your form.,What to do to ‘transfer’ the image-data from the rendering of the PlayCanvas-content behind HTML-layer (now body, container, buttons etc.) to a virtual placeholder, that can then be send/submitted to the save.php?
and within it one will find two pages in the form-structure I cf’ed earlier/above. Here is a shortened version of the original github-example — a Div referenced by ‘target’:
This is sample implementation
Going back to the top the form-structure (still in first index.php) that uses this to send/submit/(transfer image data):
Finally the save.php, in the receiving end, treats the data (from the POST):
Actual problem A) Converting ‘target+img_val’ to ‘container+container’ like:
Mouse.prototype.capture = function () < $('.container').html2canvas(< onrendered: function (canvas) < //Set hidden field's value to image data (base-64 string) $('.container').val(canvas.toDataURL("image/png")); //Submit the form manually document.getElementById("myForm").submit(); >>); >;
Источник
Saving canvas data to an image file with JavaScript and PHP Saving HTML canvas element data to an image in a user friendly manner is a tricky problem. Let’s look at one way to solve it.
First Attempt# We could always open our canvas in a new browser tab (or window) with the toDataURL JavaScript method.
window.location.href = canvas.toDataURL("image/png");
Unfortunately this requires the user to use the file menu or the right-click button to save the image from the newly opened browser tab. I wouldn’t call this user friendly.
Second Attempt# After some investigation I came across Nihilogic’s Canvas2Image JavaScript package. This package presents a Dialog Box to the user allowing them to save the image. This would solve my problem except the downloaded filename has the format 8iqALWM5.part . If my mom encountered a filename like that she wouldn’t know what to do with it. Still not user friendly.
Final Attempt# Permadi presents a technique using PHP and AJAX that is exactly what I need. After some tweaking here’s what I came up with.
save.php# The first PHP file saves the passed in canvas data to the server at a random location determined by the md5(uniqid()) method.
$data = $_POST['data']; $file = md5(uniqid()) . '.png'; // remove "data:image/png;base64," $uri = substr($data,strpos($data,",") 1); // save to file file_put_contents($file, base64_decode($uri)); // return the filename echo json_encode($file);
We would call this via JQuery with the $.post method, filling the data parameter using the toDataURL method.
download.php# Now we can use PHP to force the download of the saved image data. You can read more about this in the PHP Manual.
$file = trim($_GET['path']); // force user to download the image if (file_exists($file)) < header('Content-Description: File Transfer'); header('Content-Type: image/png'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; >else We can use the return value of our first AJAX request as input to download.php to provide the filename.
$("#save").click(function () < $.post("save.php", , function (file) < window.location.href = "download.php?path=" file>); >);
Now when the Save link is clicked a dialog box will be presented to the user asking them to save their image.
Источник
Как сохранить HTML5 Canvas в качестве изображения на сервере? Однако, я застрял на втором шаге. После некоторой помощи от Google я нашел этот пост в блоге, который, казалось, был именно тем, что я хотел:
Что привело к JavaScript-коду:
function saveImage() < var canvasData = canvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST", "testSave.php", false); ajax.onreadystatechange = function() < console.log(ajax.responseText); >ajax.setRequestHeader("Content-Type", "application/upload"); ajax.send("imgData prettyprint-override"> ?>
Но это вообще ничего не делает.
Подробнее Googling включает этот пост в блоге, который основан на предыдущем уроке. Не совсем по-другому, но, возможно, стоит попробовать:
$data = $_POST['imgData']; $file = "/path/to/file.png"; $uri = substr($data,strpos($data, ",") + 1); file_put_contents($file, base64_decode($uri)); echo $file;
Этот файл создает файл (yay), но его повреждение и, похоже, ничего не содержит. Он также кажется пустым (размер файла равен 0).
Есть ли что-то действительно очевидное, что Im делает неправильно? Путь, где Im, сохраняющий мой файл, доступен для записи, поэтому это не проблема, но ничего похожего не происходит, и я не совсем уверен, как отлаживать это.
Изменить Следуя ссылке Salvidor Dalis, я изменил запрос AJAX следующим образом:
2) Преобразование изображения холста в формат URL (base64)
var dataURL = canvas.toDataURL();
3) Отправьте его на ваш сервер через Ajax
3) Сохранить base64 на вашем сервере как образ (здесь как это сделать в PHP, те же идеи в каждом язык. Серверная сторона в PHP может быть найдена здесь):
Я имею в виду, что файл есть, но он не открывается в моем браузере или в программе просмотра изображений, если я загружаю его.
You send it to your server as an ajax request ли этот метод подтверждения от пользователя? Или я могу молча отправить изображение с холста на сервер?
Я получаю сообщение об ошибке в веб-консоли. [16: 53: 43.227] SecurityError: Операция небезопасна. @ sharevi.com/staging/canvas.html:43 Это соединение небезопасно. Есть ли что-то, что должно быть сделано? /// ОБНОВЛЕНИЕ Я думаю, я знаю почему, я использовал междоменные изображения
но альфа равен 0, что делает его незаполненным, то есть полностью прозрачным. независимо от того, что первые три значения.
Я играл с этой двумя неделями назад, это очень просто. Единственная проблема заключается в том, что все учебники просто говорят о сохранении изображения локально. Вот как я это сделал:
1) Я установил форму, чтобы использовать метод POST.
2) Когда пользователь выполнит рисование, он может нажать кнопку "Сохранить".
3) Когда кнопка нажата, я беру данные изображения и помещаю их в скрытое поле. После этого я отправлю форму.
document.getElementById('my_hidden').value = canvas.toDataURL('image/png'); document.forms["form1"].submit();
4) Когда форма отправлена, у меня есть этот небольшой php script:
это нормально, если я использую canvas.toDataURL ()? У меня есть динамическое расширение файла, как JPEG, PNG, GIF. Я пробовал canvas.toDataURL ('image / jpg'), но он не работает. В чем дело?
Я получаю сообщение об ошибке 413 (слишком большой запрос) при попытке отправить изображение с холста с помощью AJAX. Тогда этот подход помог мне получить изображения через.
Источник