À cette fin, vous devez effectuer une optimisation avec des fichiers image. Le redimensionnement de l'image lors du téléchargement en fait partie. Tous les principaux sites Web le font de la même manière. Si un utilisateur télécharge un fichier image de 5 Mo, il le redimensionne dans différentes tailles et le stocke sur son serveur. Cela les aide à créer leur site Web et à réduire leur budget. Maintenant, regardez comment nous pouvons le faire nous-mêmes.
PHP et HTML (index.php)
Ce fichier contient la base du balisage html de téléchargement de fichiers et un gestionnaire de téléchargement php simple
Fonction de redimensionnement (function.php) :
la fonction de redimensionnement est basée sur PHP
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | /** * Image resize * @param int $width * @param int $height */ function resize($width, $height){ /* Get original image x y*/ list($w, $h) = getimagesize($_FILES['image']['tmp_name']); /* calculate new image size with ratio */ $ratio = max($width/$w, $height/$h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* new file name */ $path = 'uploads/'.$width.'x'.$height.'_'.$_FILES['image']['name']; /* read binary data from image file */ $imgString = file_get_contents($_FILES['image']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); /* Save image */ switch ($_FILES['image']['type']) { case 'image/jpeg': imagejpeg($tmp, $path, 100); break; case 'image/png': imagepng($tmp, $path, 0); break; case 'image/gif': imagegif($tmp, $path); break; default: exit; break; } return $path; /* cleanup memory */ imagedestroy($image); imagedestroy($tmp); } |
Enregistrer un commentaire