如何解码 base64 图像并使用 PHP 写入文件

How to decode a base64 image and write to file using PHP

我目前正在尝试将图像写入我的网络服务器上的文件夹,正在写入一些内容,但它不是图像。我的 firedebugger 也给我一个错误

PHP Warning: imagecreatefromstring() : Data is not in a recognized form

写入的文件名称正确,但无法通过文本或图像程序打开。 angularJS 上传图像时,php 尝试检索的 $_POST 数据以此开头。

data:image/jpeg;base64,/9j/ 

PHP

<?php

ini_set("upload_max_filesize", "100M"); // to avoid anyone can send a gigabyte of file
ini_set("post_max_size", "101M"); // and break down the server...

define("MAX_IMGSIZE", 500000);
define("UPLOAD_DIR", (realpath("../uploads")).DIRECTORY_SEPARATOR);

require_once("functions.php");

// define("XHR", isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ? true : false : false);
// if(XHR)
// {
//  echo "yes";
// }

$errors = [];
if(!empty($_POST["img"]) && !empty($_POST["imgsize"]) && !empty($_POST["imgname"]) && !empty($_POST["filter"]))
{

    //      __________  ____  __  ___
    //     / ____/ __ \/ __ \/  |/  /
    //    / /_  / / / / /_/ / /|_/ / 
    //   / __/ / /_/ / _, _/ /  / /  
    //  /_/    \____/_/ |_/_/  /_/   
    //                               

    // or extract($_POST);
    $img     = $_POST["img"];
    $imgsize = intval($_POST["imgsize"]);
    $imgname = htmlentities(trim($_POST["imgname"]));
    $imgname = array_shift(explode('.', $imgname));
    $filter  = htmlentities($_POST["filter"]);

    if(strlen($imgname) == 0) // if image uploaded with empty name
        $errors[] = ["Error 54", "Image filename is empty"];

    if(check_base64_image($img))
        $errors[] = "Uploaded image is not valid!";

    if($imgsize >= MAX_IMGSIZE)
        $errors[] = sprintf("Uploaded image is too large! Maximum wieght is : %s Kb", MAX_IMGSIZE/1000);



    if(is_dir(UPLOAD_DIR)) // if upload directory exists
    {
        if(file_put_contents(UPLOAD_DIR."${imgname}_".time(), base64_decode($img)))
        {
            //     ____  ____  ______
            //    / __ \/ __ \/ ____/
            //   / / / / /_/ / /     
            //  / /_/ / _, _/ /___   
            //  \____/_/ |_|\____/   
            //                       
            // ALL SOUNDS GOOD --> ORC BEGIN

            if(exec("binary path... arg0 arg1", $o))
            {

                // rest of process

            }else
                $errors[] = ["Error 12", "Binary failed"];
        }else
            $errors[] = ["Error 32", "Cannot write image file"];

    }else
        $errors[] = ["Error 42", "Upload dir does not exists"];

}else
    $errors[] = "Filter and Image are required, please complete the form!";


//      __________  ____  ____  ____  _____
//     / ____/ __ \/ __ \/ __ \/ __ \/ ___/
//    / __/ / /_/ / /_/ / / / / /_/ /\__ \ 
//   / /___/ _, _/ _, _/ /_/ / _, _/___/ / 
//  /_____/_/ |_/_/ |_|\____/_/ |_|/____/  
//                                         

if(count($errors)) // check first system error, and shift them
{
    foreach($errors as $ie => $e)
    {
        if(is_array($e)) // system error, do not show in front for security
        {
            error_log($e[0]);
            unset($errors[$ie]);
        }
    }

    if(count($errors)) // if staying errors, inform the user
        exit(json_encode($errors));
}
?>


<!-- 
if(isset($_FILES['fileToUpload'])){
  $errors= array();        
  $file_name = $_FILES['fileToUpload']['name'];
  $file_size =$_FILES['fileToUpload']['size'];
  $file_tmp =$_FILES['fileToUpload']['tmp_name'];
  $file_type=$_FILES['fileToUpload']['type'];   
  $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
  $extensions = array("jpeg","jpg","png");        
  if(in_array($file_ext,$extensions )=== false){
    $errors[]="image extension not allowed, please choose a JPEG or PNG file.";
  }
  if($file_size > 2097152){
    $errors[]='File size cannot exceed 2 MB';
  }               
  if(empty($errors)==true){
    move_uploaded_file($file_tmp,"../uploads/".$file_name);
    echo " uploaded file: " . "images/" . $file_name;
  }else{
    print_r($errors);
  }
}

/*else{
  $errors= array();
  $errors[]="No image found";
  print_r($errors);
  }*/
 -->
<!-- function printArray($array){
  foreach($array as $key => $value){
    echo "$key => $value";
    if(is_array($value)){
      printArray($value);
    }
  }
} -->

发现来自 angularJS 的 header 信息是问题所在。为了解决这个问题,我删除了

data:image/jpeg;base64,

在作为 post 数据中图像的实际 base64 字符串之前。为了解决这个问题,我添加了一个执行以下操作的函数。

function headerRemove($img){
    $pos = strpos($img, ",",11);
    $img = substr($img, $pos, strlen($img));

    return img;

}

在angularJS中我发现在实际图片的base64字符串开始之前使用了一个“,”。使用索引 11 位置是因为开始查找第二个“,”的正确位置取决于图像类型是 png 还是 jpeg。