如何将base64编码的图像上传到服务器

时间:2016-06-21 22:54:08

标签: php image image-processing base64

我有jquery插件,它以base 64编码格式发送图像,我想将其存储在服务器中

这是我尝试过的事情

$post = json_decode($_POST['file'], true); $data = $post['output']['image'];

 $data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());        
$handle = new upload($data);
if ($handle->uploaded) {
  $handle->file_new_name_body = "$code";
  $handle->mime_check = true;
  $handle->allowed = array('image/*');
  $handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize         = true;
  $handle->image_x              = 600;
  $handle->image_ratio_y        = 600;
  $handle->process('/home/example/public_html/files/blog/img/');
  if ($handle->processed) {
  $file_name = $handle->file_dst_name;
  } else {
  echo "error";
  }
}

我的上面的代码图片上传类适用于每个图像,但我无法上传基本的64位编码图像,我怎样才能实现呢?

1 个答案:

答案 0 :(得分:0)

您使用的上传课程并不支持直接向其中提供base64。您最好先使用this method将临时版本保存到目录中,然后使用该类执行您需要执行的操作,然后将其删除:

$data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

require('/home/example/public_html/files/image/class.upload.php');

$code = md5(time());   
$write_dir = "/home/example/public_html/files/blog/img/";
$temp_code = "temp_".$code;

$ifp = fopen($write_dir.$temp_code, "wb"); 
fwrite($ifp, $data); 
fclose($ifp); 

$handle = new upload($write_dir.$temp_code);
if ($handle->uploaded) {
    $handle->file_new_name_body = "$code";
    $handle->mime_check = true;
    $handle->allowed = array('image/*');
    $handle->image_convert = 'jpg';
    $handle->jpeg_quality = 70;
    $handle->image_resize         = true;
    $handle->image_x              = 600;
    $handle->image_ratio_y        = 600;
    $handle->process($write_dir);
    if ($handle->processed) {
        $file_name = $handle->file_dst_name;
        unlink($write_dir.$temp_code);
    } else {
        echo "error";
    }
}