Decrease the size of a file(image) in PHP

Asked

Viewed 3,239 times

0

I own a page that uploads images. But there is a maximum size, a number of maximum KB that when exceeded do not let the upload end. I wonder if there is any way to decrease the size of the images (in KB) when they are chosen. When the image is selected, before transferring the file to my server folder, I would like to reduce the image size, because when exceeding a certain size of Kbytes, the upload is not finished. Thank you for your attention.

  • 1

    I believe that this answer I made should solve your problem: http://answall.com/a/63018/3635

2 answers

1

It is not possible to manipulate the image on the client side within the context of the question.

Plugin

One option would be to install some plugin in the client’s browser and then through this plugin would be run an image editing software previously installed in the client. This is an option that may be feasible for a small and restricted target public. For a public environment it is unviable. For both cases, the cost is high because you need to develop a plugin or maybe you can find a paid solution.

Software on the client

In a second option install a software client only to upload the images. And in this software would make communication with some image editor or within the software itself possess such a feature. So with the first option, you can be involved from scratch or buy ready-made solutions.

Manual process

Another option is to use an image editor software to make the image within the required standard. That is, a manual process. This is the most used because it is simple and without additional costs.

  • Got it.. Could you send me some example of this first option you mentioned? It would be of great help. Thank you.

  • 2

    In google, search for "plugin image editor client side" and terms similar to this.

0

It is possible to manipulate the image on the client side and reduce it before sending to the server, you use Javascript with File API + Canvas API (HTML5) and Ajax (Ajax is opitional, you can save the data of the generated image in a <input> or <textarea> hidden too), as I described in this reply /a/63018/3635

<script type="text/javascript">
function compressImage(file, MAX_WIDTH, MAX_HEIGHT, format, response) {
    var img = document.createElement("img");

    var reader = new FileReader();    
    reader.onload = function(e) {
        img.src = e.target.result;

        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");

        var width  = img.width;
        var height = img.height;

        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        } else if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }

        canvas.width = width;
        canvas.height = height;

        ctx.drawImage(img, 0, 0, width, height);

        response(
            canvas.toDataURL("image/" + format).replace(/^data[:]image\/(.*);base64,/, "")
        );
    };
    reader.readAsDataURL(file);
}

function uploadAjax(data, fileName, success, error)
{
    var oReq = new XMLHttpRequest();

    oReq.open("POST", "upload.php?filename=" + fileName, true);
    oReq.onreadystatechange = function() {
        if (oReq.readyState === 4) {
            if (oReq.status === 200) {
                success(oReq.responseText);
            } else {
                error(oReq.status);
            }
        }
    };
    oReq.send(data);
}

function enviar() {
    var filesToUpload = document.getElementById('input').files;

    //Gerar imagem com tamanho normal
    compressImage(filesToUpload[0], 800, 600, "jpeg", function(resource) {
        uploadAjax(resource, filesToUpload[0].name, function(response) {
            if (response === "OK") {
                alert("sucesso");
            } else {
                alert("Ajax: " + response);
            }
        }, function(errStatus) {
            alert("erro: " + errStatus);
        });
    });

    //Gerar imagem com thumb
    compressImage(filesToUpload[0], 150, 150, "jpeg", function(resource) {
        uploadAjax(resource, filesToUpload[0].name.replace(/\.([a-zA-Z0-9]+)$/, "_thumb.$1"), function(response) {
            if (response === "OK") {
                alert("sucesso");
            } else {
                alert("Ajax: " + response);
            }
        }, function(errStatus) {
            alert("erro: " + errStatus);
        });
    });
}
</script>

<p>
    <input type="file" value="" id="input">
    <input type="button" value="Enviar" id="send">
</p>

<script type="text/javascript">
document.getElementById('send').onclick = enviar;
</script>

PHP must be something like (/a/50982/3635):

<?php
define('PASTA_UPLOAD', '/home/user/projeto/data');

if (isset($_GET['filename']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $cl = (int) $_SERVER['CONTENT_LENGTH'];

    $tmpFile = tempnam(sys_get_temp_dir(), '~upload-');

    $file = fopen($tmpFile, 'w');
    $fh   = fopen('php://input', 'r');
    if ($file && $fh) {
        $data = '';
        while (FALSE === feof($fh)) {
            $data .= fgets($fh, 256);
        }
        fwrite($file, base64_decode($data));
    }

    if ($file) {
        fclose($file);
    }

    if ($fh) {
        fclose($fh);
    }

    echo 'OK';
    copy($tmpFile, PASTA_UPLOAD . '/' . $_GET['filename']);
} else {
    echo 'Requisição inválida';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.