questions

upload front-end cropped image to WP by ajax

Rate this post

I am building a page where user will edit their profile. While changing their profile picture they should be able to crop their newly selected image. For cropping I use cropzee . After researching I found that cropped image cannot be submit without ajax because cropped image cannot be added to <input type = 'file' > by javascript code. The only way is cropped image data can be sent to back-end as blob or data-url form.
My questions are:
1) How can I then handle this data to upload to wordpress media?
2) I there another way without using blob or data-url?
3) Can wordpres media uploader be used? How?

 

✔️Solution:

Check the cropzee documentation to know how to setup this plugin then follow the instructions below.

  1. Set return type to data-url
jQuery("#cropzee-input").cropzee({
      returnImageMode: 'data-url',

    });
  1. Send image data to backend by ajax
ajaxRequ.send(cropzeeGetImage('cropzee-input'));
[ Assuming you know about ‘ajax with wordpress’ if not google it first then come back here]
  1. Convert data-url to image and keep it in a custom folder.
<?php
function base64_to_jpeg($base64_string) {
    // open the output file for writing
$token = rand();
global $current_user;
  wp_get_current_user() ;
  //create a directory
mkdir(get_template_directory().'/temp');
//give a unique name to the image you may use username
$temp_path = get_template_directory().'/temp/profile_pic_'.$current_user->user_login.'.jpg';

// open the file to write the image data
    $ifp = fopen($temp_path,'w' ) or die(); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // write image data
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 
    
exit();
    
}
add_action("wp_ajax_temp_profile_pic","temp_profile_pic");
function temp_profile_pic(){
  
  $bsestring = file_get_contents("php://input");
  base64_to_jpeg($bsestring);



  wp_die();
}

  1. Finally attach it as wordpress attachment
 // to use media_handle_sideload() include the following
  require_once(ABSPATH . 'wp-admin/includes/image.php');
  require_once(ABSPATH . 'wp-admin/includes/file.php');
  require_once(ABSPATH . 'wp-admin/includes/media.php');
  
  $temp_path = get_template_directory().'/temp/profile_pic_'.$current_user->user_login.'.jpg';
//check if file exists
  if (file_exists($temp_path)) {
// check whether it is real image or not
    if (getimagesize($temp_path)) {
      $final_path = wp_upload_dir()['path'].'/'.pathinfo($temp_path, PATHINFO_BASENAME);
      //create file array
      $tmp = download_url(get_template_directory_uri().'/temp/profile_pic_'.$current_user->user_login.'.jpg');
      $file_array = array(
        'name' => basename(get_template_directory_uri().'/temp/profile_pic_'.$current_user->user_login.'.jpg'),
        'tmp_name' => $tmp
      );
   
    
//upload it to wp media upload directory
      $upload = media_handle_sideload($file_array, 0);
   
      if (empty($upload)) {
        echo "Successfully Uploaded"
      } elseif (!empty($upload)) {
        echo "Upload Failed!"
}
      

        
      }
//delete existing photo
      @unlink($tmp);
    }
  }
}


?>

You may check various conditions to make the operation more precise. Of course the operation can be done without ajax. Simply put the data url to html textarea element and submit it then process it.

Leave a Reply

Your email address will not be published.

Back to top button