如何保存base64图像服务器端

时间:2017-02-08 00:57:16

标签: php server-side

我如何保存图像服务器端我有这个代码,但由于某种原因,我上传到服务器的图像保存为text / x-generic。我该怎么做才能解决这个问题?



<?php

  function base64_to_image($base64_string) {

      $data = explode(',', $base64_string);
      $ext = "";
      switch ($data[0]) {
          case "data:image/png;base64";
              $ext = "png";
              break;
          case "data:image/jpg;base64";
              $ext = "jpg";
              break;
          case "data:image/jpeg;base64";
              $ext = "jpg";
              break;
          case "data:image/gif;base64";
              $ext = "gif";
              break;
      }

      $milli = round(microtime(true) * 1000);

      $output_file = "img/" . date('Y-m-d_H:i:s') . "." . $milli . "." . $ext; 
      $ifp = fopen($output_file, "wb"); 

    
      fwrite($ifp, base64_decode($data[1])); 
      fclose($ifp); 

      return $ifp; 

  }

  $file = base64_to_image($_POST['file']);
  var_dump($file);
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

我使用此功能来保存base64图像并且它正常工作。试试这个 -

function saveBase64ImagePng($base64Image, $imageDir)
{
    //set name of the image file

    $fileName =  'test.png';

    $base64Image = trim($base64Image);
    $base64Image = str_replace('data:image/png;base64,', '', $base64Image);
    $base64Image = str_replace('data:image/jpg;base64,', '', $base64Image);
    $base64Image = str_replace('data:image/jpeg;base64,', '', $base64Image);
    $base64Image = str_replace('data:image/gif;base64,', '', $base64Image);
    $base64Image = str_replace(' ', '+', $base64Image);

    $imageData = base64_decode($base64Image);
    //Set image whole path here 
    $filePath = $imageDir . $fileName;


   file_put_contents($filePath, $imageData);


}

希望这会对你有所帮助。