Skip to content

Instantly share code, notes, and snippets.

@ShippingGroup
Created April 28, 2021 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShippingGroup/700a59df7324a5969fdb5402d0727f5e to your computer and use it in GitHub Desktop.
Save ShippingGroup/700a59df7324a5969fdb5402d0727f5e to your computer and use it in GitHub Desktop.
/********************************************
**** EDITAR IMAGEN COMMERCE *******
*********************************************/
$app->post("/updateimage",function() use ($db,$app){
function generateRandom($longitud) {
$key = '';
$pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
$max = strlen($pattern)-1;
for($i=0;$i < $longitud;$i++) $key .= $pattern{mt_rand(0,$max)};
return $key;
}
function is_valid_email($str){
return (false !== filter_var($str, FILTER_VALIDATE_EMAIL));
}
function validateDate($date, $format = 'Y-m-d'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
$idCommerce = $app->request->post("idcommercio");
$esadmin = $app->request->post("esadmin");
$owner = $app->request->post("codereferente");
$name = $_FILES['url_fotos']['name'];
if(empty($name) || is_null($name)){
$url_profile = "images/default.png";
}else{
$baseName = basename($_FILES['url_fotos']['tmp_name']);
$size = $_FILES['url_fotos']['size'];
$type = $_FILES['url_fotos']['type'];
$tmpName = $_FILES['url_fotos']['tmp_name'];
if($type != "image/png"){
if($type != "image/jpeg"){
if($type != "image/jpg"){
echo json_encode(array("status"=>1,"messege"=>"Las imágenes soportadas por el momento son (JPG | JPEG | PNG). En su lugar estás enviando ".$type));
exit;
}
}
}
/*=============================================
DEFINIMOS LAS MEDIDAS
=============================================*/
list($ancho, $alto) = getimagesize($tmpName);
$nuevoAncho = 900;
$nuevoAlto = 600;
/*====================================================================
CREAMOS EL DIRECTORIO DONDE VAMOS A GUARDAR LA FOTO DE LA MULTIMEDIA
====================================================================*/
$url_entorno=$app->request->put("url_entorno");
if(is_null($url_entorno)){
echo json_encode(array("status"=>1,"messege"=>"El atributo url_entorno es obligatorio."));
exit;
}
if(empty($url_entorno)){
echo json_encode(array("status"=>1,"messege"=>"El atributo url_entorno es obligatorio y debe tener un valor. Revise el tipo de dato."));
exit;
}
$directorio=$_SERVER['DOCUMENT_ROOT'].'/'.$url_entorno;
/*=============================================
PRIMERO PREGUNTAMOS SI EXISTE UN DIRECTORIO DE MULTIMEDIA CON ESTA RUTA
=============================================*/
if (!file_exists($directorio)){
mkdir($directorio, 0755);
}
/*=============================================
DE ACUERDO AL TIPO DE IMAGEN APLICAMOS LAS FUNCIONES POR DEFECTO DE PHP
=============================================*/
$img_original = imagecreatefromstring(
file_get_contents($tmpName)
);
if ($img_original === false) {
echo json_encode(array("status"=>1,"messege"=>"Formato de imagen no soportado"));
exit;
}
$prefix=generateRandom(3);
$finfix=generateRandom(2);
$info = new SplFileInfo($name);
$ext=$info->getExtension();
$rutaMultimedia = $directorio.$prefix."_profile_".$finfix.".".$ext;
$max_ancho = 900;
$max_alto = 600;
list($ancho, $alto) = getimagesize($tmpName);
$x_ratio = $max_ancho / $ancho;
$y_ratio = $max_alto / $alto;
$ancho_final = $max_ancho;
$alto_final = $max_alto;
/* Creamos la imagen de destino */
$tmp = imagecreatetruecolor($ancho_final, $alto_final);
/* Alojamos el color de fondo y rellenamos con él la imagen */
$fondo = imagecolorallocate($tmp, 255, 255, 255);
imagefill($tmp, 0, 0, $fondo);
/* Con "true" forzamos la mezcla de la imagen usando la transparencia */
imagealphablending($tmp, true);
/* Copiamos la imagen con mezcla de transparencia */
imagecopyresampled(
$tmp, $img_original,
0, 0, 0, 0,
$ancho_final,
$alto_final,
$ancho,
$alto
);
/* Damos salida a la imagen en formato JPEG (100% implica pérdida de calidad)
Cuidado con $rutaCompleta que podría contener una extensión errónea */
$calidad = 100;
//imagejpeg($tmp, $rutaMultimedia, $calidad);
/* O podemos dar salida a la imagen en formato PNG (sin pérdida de calidad) */
if(imagepng($tmp, $rutaMultimedia)){
$info = new SplFileInfo($name);
$ext=$info->getExtension();
$url_profile = 'images/'.$prefix."_profile_".$finfix.".".$ext;
}
}
if($esadmin=="1"){//Si es administrador
$filtroOwner = "where id = '".$idCommerce."' ";//No filtrar por code
}else{
if($code=="777"){//Si tiene código 777, entonces tiene que ver todo
$filtroOwner = "where id = '".$idCommerce."' ";
}else{//Si no es admin ni súper admin, entonces filtro por su código.
$filtroOwner = "where id = '".$idCommerce."' and owner = '".$owner."' ";
}
}
$query = $db->query("UPDATE `bj_locales`
SET url_fotos = '".$url_profile."'
$filtroOwner ");
if($query){
echo json_encode(array("status"=>0, "messege"=>"Imagen actualizada con éxito", "urlimage"=>$url_profile));
}else{
echo json_encode( array("status"=>1 , "messege"=>$db->error) );
}
});
Ejemplo de subida
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment