Skip to main content

Yii : Image resize before ajax upload

File input control in form:

<div class="row">
            <img id="preview" width="200px" class="hidden"/>
            <?php echo CHtml::label("File Foto", 'file_image'); ?>
            <?php echo CHtml::fileField("file_image", '', array('accept' => '.jpg')); ?>
           
            <br/>
            <?php
            echo CHtml::button("Upload Foto", array(
                'id' => 'btn-upload'
            ));
            ?>
</div>


Button onclick event:


Yii::app()->clientScript->registerScript('upload', "
    $('#btn-upload').click(function(){        
        resizeImage();
    });
");


Javascript function :

<script>
    function upload(dataurl) {
        var formData = new FormData($("#tbl-hdrclaimrusak-form")[0]);
        formData.append("image_compress", dataurl);
        formData.delete("file_image");
        $.ajax({
            url: '<?php echo Yii::app()->createUrl("someController/ajaxupload"); ?>',
            type: 'POST',
            data: formData,
            datatype: 'json',
            success: function (data) {
                var json = $.parseJSON(data);
                if (json.message) {
                    $("#div-message").removeClass("hidden");
                    $("#div-message").html(json.message);
                } else {
                    $("#div-message").addClass("hidden");
                    $.fn.yiiGridView.update('foto_grid', {
                        data: $(this).serialize()
                    })

                }
            },
            cache: false,
            contentType: false,
            processData: false
        });
    }
    
    function resizeInCanvas(img) {
        var preferedWidth = 1024;
        if (img.width < img.height) {
            preferedWidth = 768;
        }
        var ratio = preferedWidth / img.width;
        var canvas = document.createElement("canvas");
        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        return canvas.toDataURL("image/jpeg");
    }

    function resizeImage() {
        Loading.show();
        var input = document.getElementById("file_image");
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image();
                img.src = e.target.result;
                var dataurl = resizeInCanvas(img);
                upload(dataurl);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

</script>


PHP Controller script:


public function actionAjaxupload() {
            if (isset($_POST['image_compress'])) {
                $compressed = $_POST['image_compress'];
                $compressed = str_replace('data:image/jpeg;base64,', '', $compressed);
                $compressed = str_replace(" ", "+", $compressed);
                $new_foto = base64_decode($compressed);
                $filename = "compressed" . "_" . date("YmdHis") . ".jpeg";
                $fullpath = Yii::app()->basePath . "/../images/somefolder/" . $filename;
                $store = file_put_contents($fullpath, $new_foto);
                
            }
            echo CJSON::encode(array('message' => $message));
        
}

Comments