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

Popular posts from this blog

Ubuntu Server 16.04 : Connection via USB Android Tethering

As we know that Ubuntu Server by default does not have a GUI. It is certainly quite difficult to make internet connection via USB Android. Here's how to connect internet via USB and have been tried in Ubuntu Server version 16.04 LTS. Make sure your android phone already has internet connection Connect your android phone with server via USB cable From your android phone, click Settings menu -> Wireless and Network -> More -> Tethering & portable hotspo t and enable USB tethering In the ubuntu server terminal, use the command sudo ifconfig -a Sample display of this command enp0s29f7u5 Link encap:Ethernet HWaddr 08:00:27:38:7b:49 inet addr:192.168.201.7 Bcast:192.168.201.1 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fe38:7b49/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3593205 errors:0 dropped:0 overruns:0 frame:0 TX packets:4328737 errors:0 dropped:0 overruns:0 ...

Autostart VirtualBox VM on Ubuntu Server 18.04 Boot

Create a configuration file in /etc/default/ sudo nano /etc/default/virtualbox then add VBOXAUTOSTART_DB=/etc/vbox VBOXAUTOSTART_CONFIG=/etc/vbox/autostart.cfg Then create a configuration file in  /etc/vbox/ sudo nano /etc/vbox/autostart.cfg then add default_policy = deny # Create an entry for each user allowed to use autostart myusername = { allow = true } sudo chgrp vboxusers /etc/vbox sudo chmod 1775 /etc/vbox sudo usermod -aG vboxusers USERNAME VBoxManage setproperty autostartdbpath /etc/vbox Use the following command to get a list of available vms vboxmanage list vms Create a file with <username>.start on /etc/vbox sudo touch /etc/vbox/username.start sudo chown username /etc/vbox/username.start Restart the virtualbox service for changes to take effect sudo systemctl restart vboxautostart-service Specify the virtual machine that will be set to autostart VBoxManage modifyvm <uuid|vmname> --autostart-enabled...

Ubuntu Server 16.04: Minimum GUI

As we know that Ubuntu Server by default does not have a GUI. But sometimes in certain cases, we need a GUI on Ubuntu Server. For example Ubuntu Server as the host of the virtual client (KVM, VirtualBox, VMware or other virtual applications). Although VirtualBox has a headless server configuration, having a GUI still makes it much easier in terms of virtual client maintenance. If we do a search on google, many articles or tutorials that discuss how to install GUI on Ubuntu Server. Where in general the command used the command for the installation as follows sudo apt-get install --no-install-recommends ubuntu-desktop If the command is executed, after restarting the server, it will display a GUI like the desktop version of Ubuntu. The --no-install-recommends argument should be used to avoid unnecessary package installations, such as multimedia applications, browsers, office applications and other desktop applications commonly found on desktop ubuntu installations. In general, m...