Monday, 15 August 2016

PHP resize image before base64 encoding

It took me a while to work this out, but it was worth it. base64 encoding can be really useful in presenting and storing images on the web. However you don't want to add a 2000 pixel width base64 encoded image to your database. Here's how to resize the image before it goes in.

$file = 'mypic.jpg';
$image = imagecreatefromjpeg($file);
$image = imagescale($image , 100);
$contents = ob_get_contents();
$dataUri = "data:image/jpeg;base64,".base64_encode($contents);
echo '<img src="'.$dataUri.'" />';

Wednesday, 10 August 2016

Using jQuery FormData to include files when making POST request

In this example I create a form, with a text, and file input field. When I submit the form, contents from all input fields are submitted through the 'FormData' class. The results from the called script are returned to a div. Finally, the fields are then cleared.
    <title>jQuery File Upload</title>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
        <input type="text" name="myname" />
        <input type="file" name="fileinfo" multiple="" />
        <button type="submit">Submit</button>
    <div id="result"></div>
    <script src=""></script>
        $('form').on('submit', function(e)
            var theDiv = $('div#result');
            var thisForm = $(this);
            var action = thisForm.attr('action');
            var method = thisForm.attr('method');
                url: action,
                type: method,
                data: new FormData(this),
                processData: false,
                contentType: false
                thisForm.find('input, textarea').val('');

To test if it works I use upload.php. See
$str = NULL;
foreach($_FILES as $file)
    if(move_uploaded_file($file['tmp_name'], $file['name']) == FALSE)
        $str .= $file['name'].' not uploaded<br />';
$str .= '<br />POST items include : <br />';
foreach($_POST as $postitem => $value)
    $str .= 'Name : '.$postitem.' Value : '.$value.'<br />';
echo $str;