简体   繁体   English

Php | 验证base64_decode为图像| 不工作

[英]Php | validate base64_decode as image | Not working

I created a function that will return the filetype of the supplied base64_decode argument. 我创建了一个函数,该函数将返回提供的base64_decode参数的文件类型。 If it's not an image, the function will return false. 如果不是图像,则该函数将返回false。 However, when passing in encoded images (via jquery ajax (FormData object)) the function returns false everytime. 但是,当传入编码的图像(通过jquery ajax(FormData对象))时,该函数每次都返回false。 I have tried many things, but am unable to get it working. 我已经尝试了很多方法,但是无法使其正常工作。

EDIT: I am now getting a Javascript error, here it is : 编辑:我现在收到一个Javascript错误,这里是:
"Uncaught SyntaxError: Unexpected token in JSON at position 0" “未捕获的SyntaxError:意外的令牌。JSON位于位置0”

function base64_extension($base64){
    $base64 = str_replace("data:image/png;base64,", "", $base64);
    $base64 = base64_decode($base64);

    $base64 = imagecreatefromstring($base64);

    if(!$base64){
        return 0; /* Not image */
    }


    if(imagepng($base64)){
        imagedestroy($base64);
        return 1;
    }else if(imagejpeg($base64)){
        imagedestroy($base64);
        return 2;
    }
    else if(imagegif($base64)){
        imagedestroy($base64);
        return 3;
    }
    else{
        return 4; /* Not image */
    }
}

CLIENT 客户

var cropCanvas = $('#user-img').cropper('getCroppedCanvas');
var cropImg = cropCanvas.toDataURL("image/jpeg");
var formData = new FormData();
formData.append('pic', cropImg);

Then I pass the formData into ajax here. 然后我在这里将formData传递到ajax中。

As Jonathan Kuhn said 正如乔纳森·库恩(Jonathan Kuhn)所说

Once you have an image created with any of the imagecreate* functions, you can output any type of image like png, jpg, gif regardless of what the input format was. 使用任何imagecreate *函数创建图像后,无论输入格式是什么,都可以输出任何类型的图像,例如png,jpg,gif。 Creating the image means it is in GD's format that the extension can manipulate and then output in any image format it understands. 创建映像意味着扩展可以操纵GD格式,然后以其理解的任何图像格式输出。

So your way is wrong you can get the MIME Type of Decoded base64 with finfo_* functions. 因此,您的方法是错误的,您可以使用finfo_ *函数获取已解码base64的MIME类型。

For Example : 例如 :

$base64 = base64_decode($base64);
$finfo_handler = finfo_open();
$allowed_types = ["image/jpeg","image/png","image/gif"];
$mime_type = finfo_buffer($finfo_handler, $base64, FILEINFO_MIME_TYPE);
finfo_close($finfo_handler);
if(!in_array($mime_type, $allowed_types)){
    // Mime Type is not JPEG or PNG or GIF
    return false;
}else{
    // Mime Type is in Array and returns first index of exploded string by "/" char.
    // That means for image/jpeg exploded_array = [ 0 => "image", 1 => "jpeg"]
    // and it returns first index "jpeg" for "image/png" it returns "png"
    return explode("/", $mime_type)[1];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM