I am trying to save an image to a folder in PHP by decoding a canvas.toDataURL('image/png')
coded image. The toDataURL gives me the following string:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXYAAAF1CAYAAAD8ysHLAAAgAElEQVR4XuydCbiOVff/lw...
which is around 43 000 characters long. I send this to PHP via AJAX. Then I tried to follow some answers online how to decode it but none worked as expected. The one that came up the most is the following approach:
$img64String = $_POST['file'];
$img64String = str_replace('data:image/png;base64,', '', $img64String);
$img64String = str_replace(' ', '+', $img64String);
$fileData = base64_decode($img64String);
Line 1 gets the original string, line 2 and 3 is to remove the first part and keep everything after the comma and then replace empty places with + according to documentation. However, the 4th line gives me a result which looks something like this:
FileData: �PNG IHDRvu���� IDATx^� ��U���eʔ! !
%��Pр$C*�FC��FD��&�(RRƷdJ�䯼Pʔyʐ�����?�s�9g�������ֺ.W�s�}��|
��߽�����8�?&fF�#�@��5si�#�dka�����f�i�?
���d�1'ݔ'�#�k���Ʉ]7��V&�...
Basically a string with a bunch of nonsense (?) in it. What is going on?
If there is of any help, here is the AJAX call:
form_data = new FormData();
form_data.append('file', newImage);
form_data.append('action', 'file_upload');
form_data.append('security', blog.security);
// Send to AJAX
$.ajax({
url: blog.ajaxurl,
type: 'POST',
contentType: false,
processData: false,
data: form_data, ...
What I want
Previously I sent the uploaded file itself but now I want to resize it first, hence I used the new approach. Previously I used this on PHP side which works fine:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_temp_name = $_FILES['file']['tmp_name'];
$allowed_file_types = array('image/png', 'image/jpeg', 'image/jpg');
if (in_array($file_type, $allowed_file_types)) {
$upload = wp_upload_bits($file_name, null, file_get_contents($file_temp_name));
$status = "ok";
}
I want to get my string into something that I can use in a similar way if possible.