I am using the Cropper JS to crop an image that I am adding into a WordPress plugin I am developing.
All is fine with the cropping tool and it is sending the image as a BASE64 string via AJAX to my PHP script that I want to upload to WordPress.
I have the correct code to upload a normal image to WordPress, but the image that I pass through for that to work is a normal HTML file upload field.
I am looking for a way of either converting the BASE64 string into a format needed to work with the WordPress upload, or change the WordPress upload functionality to use the BASE64 string instead. I am not sure which is easiest / best - any ideas?
Below is the PHP code that works when passing through an image via an upload field:
<?php
add_action('wp_ajax_crop_image', 'crop_image_callback');
add_action('wp_ajax_nopriv_crop_image', 'crop_image_callback');
function crop_image_callback()
{
check_ajax_referer('crop_image', 'security');
$arr_img_ext = array('image/png', 'image/jpeg', 'image/jpg', 'image/gif');
if (in_array($_FILES['file']['type'], $arr_img_ext)) {
$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
if (!$upload['error']) {
$post_id = $_POST['post_id'];
$filename = $upload['file'];
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
update_post_meta($post_id, 'plain_image', $attachment_id);
}
}
echo $upload['url'];
}
wp_die();
}
?>
The BASE64 image string of the cropped image is being passed via POST, as such $_POST['image'];
I can show the jQuery/AJAX if necessary, but that part is working correctly and sending over the string. It is just the PHP code that I want to update to be able to upload that BASE64 string to the WordPress media.