如何将base64转换为php POST表单中的图像

问题描述

我使用croppiejs在表单中裁剪我的图像,然后我将结果图像作为base64存储在隐藏输入中并将post值传递给PHP,现在我需要一个PHP代码来帮助我将Base64裁剪图像转换为实际图像并将其保存在“../images”文件夹中,这怎么可能?任何代码将不胜感激!

        $title= $_POST["news_title"];
        $date= $_POST["news_date"];
        $time= $_POST["news_time"];
        $context= $_POST["news_context"];
                $img= $_POST["baseimg"]; // Base64 cropped image (contains data:image/png;base64)

$news_context= stripslashes($_POST['news_context']);
                    $news_context1= MysqLi_real_escape_string($conn,$news_context);
                if (!empty($title) && !empty($date) && !empty($time) && !empty($news_context) ) {

// Need the code here

}

解决方法

以下可用于将 dataURL 转换为真实的 PNG 图像。我在流行网站上存储大量图像方面有很多经验。让我建议不要将它们存储在您将要设置的数据库中。而是将图像存储在文件系统上,然后将该图像的唯一名称放入您的数据库中。

$title = $_POST["news_title"];
$date = $_POST["news_date"];
$time = $_POST["news_time"];
$context = $_POST["news_context"];
$img = $_POST["baseimg"]; // Base64 cropped image (contains data:image/png;base64)

$news_context = stripslashes($_POST['news_context']);
$news_context1 = mysqli_real_escape_string($conn,$news_context);
if (!empty($title) && !empty($date) && !empty($time) && !empty($news_context)) {
    list($type,$data) = explode(';',$img);
    list(,$data)      = explode(',',$data);
    $data = base64_decode($data);

    // This will place the image in /tmp/image.png
    file_put_contents('../images/image.png',$data);

    // Need the code here
}