Coilerz Coilerz - 7 months ago 26
PHP Question

Base64 clipping images

The following code is taking a base64 string provided by a plugin called cropit and converting it to an image.

list($type, $base64) = explode(';', $base64);
list(, $base64) = explode(',', $base64);
$base64 = str_replace("data:image/jpeg;base64,", "", $base64);
$base64 = base64_decode($base64);

file_put_contents($directory, $base64);


I'll also provide my javascript that is sending the base64 to the php function through the use of an input. I know that the issue is being caused by PHP because when I send
imageData
to a new window the image will show up perfectly with no issues.

$('.export_upload').click(function() {
$("#upload_form_identifier").val("upload_form");

var imageData = $('.image-editor-upload').cropit('export', {
type: 'image/jpeg',
quality: 0.3,
originalSize: true
});

//Set value of hidden input to base64
$("#hidden_base64_upload").val(imageData);

//Pause form submission until input is populated
window.setTimeout(function() {
document.upload_form.submit();
}, 1000);
});


The issue I'm having is that if I input an image it will clip it in a random spot. Could PHP be running out of memory? I'm not very experience with base64 so I really don't have any idea what could be causing this. Any help would be great.

Original Image:
Original Image

After PHP processes base64:
After PHP processes base64

Answer

Although this isn't the best solution it works for me and will probably suit your needs. The issue I've found is with originalSize: true having this will export the cropped part of the image without any compression resulting in a very large base64. The way I solve it is by setting originalSize to false and then resizing the preview to a size that I will use. The code below should work.

$('.export_upload').click(function() {
            $("#upload_form_identifier").val("upload_form");

            $('.image-editor-upload').cropit('previewSize', {width:1024, height:1024});

            var imageData = $('.image-editor-upload').cropit('export', {
                type: 'image/jpeg',
                quality: .75,
                originalSize: false
            });



            //Set value of hidden input to base64
            $("#hidden_base64_upload").val(imageData);

            //Pause form submission until input is populated
            window.setTimeout(function() {
                window.open(imageData);
                document.upload_form.submit();
            }, 1000);
        });

The key is $('.image-editor-upload').cropit('previewSize', {width:1024, height:1024});. This resizes the image before sending it to the php function. The only real issue with this is that if the user modifies the javascript they will be able to change the output size of the image but this shouldn't be an issue if you verify the upload with php to ensure the Width and height match what you put inside of the brackets.