Convert image size before uploading PHP

Asked

Viewed 1,401 times

0

Colleagues,

I have a code from which after uploading to the directory, it decreases the image and replaces the upload image. See:

$c = 0;
foreach($fotos['name'] as $foto){

$tempProd = $fotos['tmp_name'][$c++];
$extensoesProd = array('png', 'jpg');
$validarProd = pathinfo($fotosProd, PATHINFO_EXTENSION);
list($nomeFotoProd,$extensaoFotoProd) = explode($validarProd,$fotosProd);
$nomeFotoProd = md5($nomeFotoProd).".".$validarProd;

if(move_uploaded_file($tempProd, '../../projeto-final/produtos/'.$nomeFotoProd)){

            $diretorioNormal = "../../projeto-final/produtos/";
            $fotoDir = $diretorioNormal.$nomeFotoProd;
            list($largura,$altura) = getimagesize($fotoDir);
            $novaLargura = 997;
            $novaAltura = 665;
            $miniatura = imagecreatetruecolor($novaLargura, $novaAltura);
            $imagem = imagecreatefromjpeg($fotoDir);
            imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $novaLargura, $novaAltura, $largura, $altura);
            imagejpeg($miniatura,$fotoDir,90);
    ....
    }
}

So far it works correctly, but you have to convert the image before playing it to the server without having to do this process of going up and replace?

2 answers

1

You can achieve this with Javascript (Canvas API, Filereader API and Ajax), examples:

Example using Canvas, FileReader and Ajax:

<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 should look something like:

<?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';
}

It is also possible using other technologies like Flash and Java Applet, but npapi has stopped working on many browsers and some browsers like Chrome are disabling Flash by default.

0

I found something that might help you:

compress-compress-image-upload

But basically, you need to make a case to filter different extensions and use each imagecreatefrom*() to its respective extent:

$imagemTmp=imagecreatefromjpeg($imagemOriginal);
$imagejpeg($imagemTmp, $imagemFinal, $qualidade);
$imagedestroy($imagemTmp);

--

If you want images with unique name, you will have problem. Use:

// Gera um identificador único para o arquivo
$nomeFotoProd = md5(uniqid(rand(), true)).".".$validarProd;

Instead of:

$nomeFotoProd = md5($nomeFotoProd).".".$validarProd;

(If I upload an image with the same name it will be replaced)

  • The question is: but has to convert the image before playing it to the server without having to do this process of going up and replace?, is not a problem in PHP but rather in image compression on the client-side layer.

  • 1

    I get it, agree with you, I had a misinterpretation of the question haha. regarding using the flash I wouldn’t even quote it because besides depreciation is a Swiss cheese in safety.

  • I just quoted to him understand the clients-side layer ;) ... Flash really does not bring but no advantage, at most as fallback. Until more the/

Browser other questions tagged

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