Good morning, how do I compress an image before uploading it to the server, I have tried to add the code to compress it but it does not work, in the attached code my script to compress the image before uploading it but it does not work, if someone can help me I would appreciate them.
// code
<?php
$txtNombre=(isset($_POST['valor_t2']))?$_POST['valor_t2']:"";
$txtFoto=(isset($_FILES['txtFoto']["name"]))?$_FILES['txtFoto']["name"]:"";
include ("conexion/conexion.php");
$sentencia=$pdo->prepare("INSERT INTO empleados(valor_t2,foto) VALUES (:valor_t2,:foto)");
$sentencia->bindParam(':valor_t2',$txtNombre);
$Fecha = new DateTime();
$nombreArchivo=($txtFoto!="")?$Fecha->getTimestamp()."_".$_FILES["txtFoto"]["name"]:"default.jpg";
$tmpFoto = $_FILES["txtFoto"]["tmp_name"];
if($tmpFoto!=""){
move_uploaded_file($tmpFoto,"Imagenes/".$nombreArchivo);
}
//codigo que intente agregar para comprimir la imagen pero no funciona
////////////////////////////////////
function comprimirImagen($recurso, $destino, $calidad) {
$imgInfo = getimagesize($recurso);
$mime = $imgInfo['mime'];
//Creamos una imagen temporal
switch($mime){
case 'image/jpeg':
$imagen = imagecreatefromjpeg($recurso);
break;
case 'image/png':
$imagen = imagecreatefrompng($recurso);
break;
case 'image/gif':
$imagen = imagecreatefromgif($recurso);
break;
default:
$imagen = imagecreatefromjpeg($recurso);
}
// Guardamos la imagen
imagejpeg($imagen, $destino, $calidad);
comprimirImagen($_FILES["txtFoto"]["tmp_name"],'',80);
///////////////////////////////////
$sentencia->bindParam(':foto',$nombreArchivo);
$sentencia->execute();
?>
the way to use it is as follows, compressImage() receives 3 arguments, the first is the temporary path of the image, the second is the path of the destination file with the modification made, the third is the quality with which you want it to be compressed, I suggest you put no less than 70%
usage example
The ideal is that you compress the image before uploading it to the backend, that is, in the frontend, in the javascript, you can use this example Here is an example of how to do it Then you will have to add the blob in the FormData and send it, like this in the backend you will receive a compressed image