0

I’m creating a custom back-end API to update a user avatar image via user id. So i send via post REST request this parameters:

user_id : The id of the user;

– image: base64 image;

image_name: the image name.

This is the php code that i use to update the avatar image but it doesn’t works 🙁

// Get URL data
global $json_api
$user_id = $json_api->query->user_id;
$image = $json_api->query->image;
$image_name = $json_api->query->image_name;
$image = str_replace('data:image/jpeg;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$hashed_filename = md5( $image_name . microtime() ) . '_bpthumb.jpg';
$data = base64_decode($image);
$success = file_put_contents('/wp-content/uploads/avatars/'.$user_id.'/'.$hashed_filename, $data);

$success variable returns always false T.T

Thank you in advance for the help and sorry for my english.

  • Try github.com/buddypress/BP-REST – shanebp Mar 15 at 11:17
  • @shagebp Thank you for reply but BP-REST doesn't help me :( i've found at this thread link a code that seems to work but i've some problem if i change the path of the avatar image from file_put_contents($uploaddir["path"].'/'.$avatar,$imgdata); to file_put_contents($uploaddir["path"].'/'.$user_id.'/'.$avatar,$imgdata); – Biagio Pietro Capece Mar 22 at 17:32
0

I finally found a SOLUTION and i want to post it because can be useful for someone!

public function update_user_avatar() 
{
   global $json_api;
   if (!$json_api->query->user_id) 
   {
      $json_api->error("Missing 'user_id' parameter.");
   }
   if (!$json_api->query->image) 
   {
     $json_api->error("Missing 'image' parameter.");
   }
   $user_id = $json_api->query->user_id;
   $base64 = $json_api->query->image;

   $imgdata            =   base64_decode($base64);
   $f = finfo_open();
   $mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
   $type_file = explode('/', $mime_type);
   $time = time();
   $avatar_thumb = $time . '-bpthumb.' . $type_file[1];
   $avatar_full = $time . '-bpfull.' . $type_file[1];

   $uploaddir = wp_upload_dir(); 
   $myDirPath = $uploaddir["path"]; 
   $myDirUrl = $uploaddir["url"];
   $upload_path = '/home/<folder>/public_html/wp-content/uploads/avatars/'.$user_id;

   // Create user id folder if not exist for avatar image
   if (!file_exists($upload_path)) 
   {
       mkdir($upload_path, 0755, true);
   }
   require_once(ABSPATH . '/wp-load.php');             
   require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
   require_once(ABSPATH . 'wp-admin' . '/includes/image.php');

   // Remove files into user's folder
   $files = list_files($upload_path);
   for($i = 0; $i<count($files); $i++)
   {
     wp_delete_file($files[$i]);
   }

   file_put_contents($upload_path.'/'.$avatar_thumb,$imgdata);
   file_put_contents($upload_path.'/'.$avatar_full,$imgdata);
   switch ($type_file[1]) {
     case 'jpeg':
       # code...
       $img_full = $this->resize_imagejpg($upload_path.'/'.$avatar_full, 150, 150);
       $img_thumb = $this->resize_imagejpg($upload_path.'/'.$avatar_thumb, 50, 50);
       break;
     case 'jpg':
       # code...
       $img_full = $this->resize_imagejpg($upload_path.'/'.$avatar_full, 150, 150);
       $img_thumb = $this->resize_imagejpg($upload_path.'/'.$avatar_thumb, 50, 50);
       break;
     case 'png':
       # code...
       $img_full = $this->resize_imagepng($upload_path.'/'.$avatar_full, 150, 150);
       $img_thumb = $this->resize_imagepng($upload_path.'/'.$avatar_thumb, 50, 50);
       break;
     case 'gif':
       # code...
       $img_full = $this->resize_imagegif($upload_path.'/'.$avatar_full, 150, 150);
       $img_thumb = $this->resize_imagegif($upload_path.'/'.$avatar_thumb, 50, 50);
       break;
     default:
        return array(
               "success" => false,
               "avatar_url" => get_avatar_url($user_id));
        break;
   }
   // Override previous image
   imagejpeg($img_thumb, $$upload_path.'/'.$avatar_full, 100);
   imagejpeg($img_full, $upload_path.'/'.$avatar_thumb);

   $filename = $myDirUrl.'/'.basename( $avatar_thumb );
   $wp_filetype = wp_check_filetype(basename($filename), null );
   $uploadfile = $upload_path.'/'. basename( $filename );           
   $attachment = array(
      "post_mime_type" => $wp_filetype["type"],
      "post_title" => preg_replace("/\.[^.]+$/", "" , basename( $filename )),
      "post_content" => "",
      "post_status" => "inherit",
      'guid' => $uploadfile,
   );              


   $attachment_id = wp_insert_attachment( $attachment, $uploadfile );

   update_post_meta($attachment_id,'_wp_attachment_wp_user_avatar',$user_id);
   update_user_meta($user_id, 'wp_user_avatar', $attachment_id);
   return array(
     "success" => true,
     "avatar_url_thumb" => get_avatar_url($user_id),
     "avatar_url_full" => $this->get_avatar_url_full($user_id));
 }

These are methods to resize the image (Code from this answer https://stackoverflow.com/questions/14649645/resize-image-in-php):

 // for jpg 
  private function resize_imagejpg($file, $w, $h) {
     list($width, $height) = getimagesize($file);
     $src = imagecreatefromjpeg($file);
     $dst = imagecreatetruecolor($w, $h);
     imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
     return $dst;
  }

   // for png
  private function resize_imagepng($file, $w, $h) {
     list($width, $height) = getimagesize($file);
     $src = imagecreatefrompng($file);
     $dst = imagecreatetruecolor($w, $h);
     imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
     return $dst;
  }

  // for gif
  private function resize_imagegif($file, $w, $h) {
     list($width, $height) = getimagesize($file);
     $src = imagecreatefromgif($file);
     $dst = imagecreatetruecolor($w, $h);
     imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
     return $dst;
  }

This is a function that i wrote to retrieve the full avatar image url:

private function get_avatar_url_full($user_id)
{
    require_once(ABSPATH . '/wp-load.php');             
    require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
    require_once(ABSPATH . 'wp-admin' . '/includes/image.php');
    $upload_path = '/home/<folder>/public_html/wp-content/uploads/avatars/'.$user_id;
    $files = list_files($upload_path);
    if (count($files) == 0 || count($files) == 1)
    {
        return get_avatar_url($user_id);
    }
    else
    {
      for($i = 0; $i<count($files); $i++)
      {
        if(strpos($files[$i], '-bpfull.'))
        {
          $avatar_full_name = explode('/', $files[$i]);
          $url = htmlspecialchars("https://www.example.com/wp-content/uploads/avatars/");
          return $url.$user_id.'/'.$avatar_full_name[count($avatar_full_name)-1];
        }
      }
      return get_avatar_url($user_id);
    }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.