phpjquerybase64croppie

How to convert base64 to image in php POST form


I used croppiejs to crop my images in a form, then i stored the result image as base64 in a hidden input and passed the post value to PHP, now I need a php code to help me convert the Base64 cropped image to an actual image and save it in "../images" folder, How can this be possible? any code will be appreciated!

        $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

}

Solution

  • The below could be used to translate the dataURL into a real PNG image. I have a lot of experience in storing large amounts of images on popular sites. Let me suggest to not store them in a database which looks like you are going to be setting up to do. Instead store the images on a filesystem then put a unique name for that image in your database.

    $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
    }