Foros del Web » Programando para Internet » PHP »

obtener de que tipo es una imagen

Estas en el tema de obtener de que tipo es una imagen en el foro de PHP en Foros del Web. tengo un php en el que subo imagenes todo va bien el problema es que tengo que renombrar la imagen con rename entonces necesito saber ...
  #1 (permalink)  
Antiguo 27/02/2011, 13:54
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Exclamación obtener de que tipo es una imagen

tengo un php en el que subo imagenes todo va bien el problema es que tengo que renombrar la imagen con rename entonces necesito saber de que formato es la imagen si .jpg .png o .gif

la imagen la recibo como file

rename("temp/imagen.el formato", "temp/nuevo nombre. el fotmato);
  #2 (permalink)  
Antiguo 27/02/2011, 14:00
 
Fecha de Ingreso: octubre-2009
Mensajes: 245
Antigüedad: 14 años, 6 meses
Puntos: 17
Respuesta: obtener de que tipo es una imagen

http://www.php.net/manual/es/feature...ost-method.php
__________________
Saludos.
  #3 (permalink)  
Antiguo 27/02/2011, 14:16
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

si el formato lo recojo asi

$userfile_type = $_FILES['image']['type'];

pero como deveria reflejarlo aqui

rename("temp/imagen.el formato", "temp/nuevo nombre. el fotmato);

para que el resultado fuese el siguiente si el formato fuese por ejemplo png

rename("temp/imagen.png", "temp/nuevo nombre.png);
  #4 (permalink)  
Antiguo 27/02/2011, 14:21
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 5 meses
Puntos: 25
Respuesta: obtener de que tipo es una imagen

para cambiar el nombre de imagen hay mas de un post en el mismo foro vea esto:
http://www.forosdelweb.com/f18/subir...nombre-536527/
__________________
cada vez que aprendes algo te crees que no sabes nada
  #5 (permalink)  
Antiguo 27/02/2011, 14:36
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

nada sigue sin recogerme el formato
  #6 (permalink)  
Antiguo 27/02/2011, 14:52
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

probe con esto

$sep=explode('image/',$_FILES["image"]["type"]); // Separamos image/
$tipo=$sep[1]; // Optenemos el tipo de imagen que es
if($tipo == "gif" || $tipo == "pjpeg" || $tipo == "bmp" || $tipo == "png" || $tipo == "pjpeg"){
}echo $tipo;

y no me muestra el formato tampoco
  #7 (permalink)  
Antiguo 27/02/2011, 14:55
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 5 meses
Puntos: 25
Respuesta: obtener de que tipo es una imagen

quieres saber solo el formato del imagen??
__________________
cada vez que aprendes algo te crees que no sabes nada
  #8 (permalink)  
Antiguo 27/02/2011, 15:00
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

si solo si es .jpg .png .bmp....

entonces si lo pongo en

echo $formato;

me salga

.jpg o lo que sea
  #9 (permalink)  
Antiguo 27/02/2011, 15:04
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 5 meses
Puntos: 25
Respuesta: obtener de que tipo es una imagen

en este caso yo lo haria con if ejemplo:
Código PHP:
Ver original
  1. <?php
  2.  if ($_FILES['imagefile']['type'] == "image/jpg" ){echo 'El formato de la imagen es jpg';}
  3.  if($_FILES['imagefile']['type'] == "image/png"){echo 'El formato de la imagen es png';}
  4.  if($_FILES['imagefile']['type'] == "image/bmp") {echo 'El formato de la imagen es bmp';}
  5. ?>
__________________
cada vez que aprendes algo te crees que no sabes nada
  #10 (permalink)  
Antiguo 27/02/2011, 15:14
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

voy a probar gracias
  #11 (permalink)  
Antiguo 27/02/2011, 15:15
marcofbb
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: obtener de que tipo es una imagen

Ojo, si lo haces como dicen arriba, tiene bugs y se puede hackear con bypass

Te recomiendo este:

http://www.marcofbb.com.ar/upload-de-imagenes/
  #12 (permalink)  
Antiguo 27/02/2011, 15:17
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 5 meses
Puntos: 25
Respuesta: obtener de que tipo es una imagen

es solo para comprobar el tipo de imagen amigo no para subir la
__________________
cada vez que aprendes algo te crees que no sabes nada
  #13 (permalink)  
Antiguo 27/02/2011, 15:22
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

de todas maneras no me lo muestra aun.....
  #14 (permalink)  
Antiguo 27/02/2011, 15:24
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 5 meses
Puntos: 25
Respuesta: obtener de que tipo es una imagen

por que no pones el codico
__________________
cada vez que aprendes algo te crees que no sabes nada
  #15 (permalink)  
Antiguo 27/02/2011, 15:31
Avatar de alfoner  
Fecha de Ingreso: abril-2009
Mensajes: 146
Antigüedad: 15 años
Puntos: 0
Respuesta: obtener de que tipo es una imagen

<?php


error_reporting (E_ALL ^ E_NOTICE);
session_start(); //Do not remove this
//only assign a new timestamp if the session variable is empty
if (!isset($_SESSION['random_key']) || strlen($_SESSION['random_key'])==0){
$_SESSION['random_key'] = strtotime(date('Y-m-d H:i:s')); //assign the timestamp to the session variable
$_SESSION['user_file_ext']= "";

}

################################################## ################################################## #####
# CONSTANTS #
# You can alter the options below #
################################################## ################################################## #####



$upload_dir = "temp"; // The directory for the images to be saved in
$upload_path = $upload_dir."/"; // The path to where the image will be saved
$large_image_prefix = "original"; // The prefix name to large image
$thumb_image_prefix = "copia"; // The prefix name to the thumb image
$large_image_name = $large_image_prefix.$_SESSION['']; // New name of the large image (append the timestamp to the filename)
$thumb_image_name = $thumb_image_prefix.$_SESSION['']; // New name of the thumbnail image (append the timestamp to the filename)
$max_file = "3"; // Maximum file size in MB
$max_height = "350";
$thumb_width = "165"; // Width of thumbnail image
$thumb_height = "124";
// Height of thumbnail image
// Only one of these image types should be allowed for upload
$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = ""; // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
$image_ext.= strtoupper($ext)." ";


}


################################################## ################################################## ######
# IMAGE FUNCTIONS #
# You do not need to alter these functions #
################################################## ################################################## ######
function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeigh t);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,0,0,$newI mageWidth,$newImageHeight,$width,$height);

switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}

chmod($image, 0777);
return $image;
}
//You do not need to alter these functions
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);

$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeigh t);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_wi dth,$start_height,$newImageWidth,$newImageHeight,$ width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
//You do not need to alter these functions
function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
//You do not need to alter these functions
function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}

//Image Locations
$large_image_location = $upload_path.$large_image_name.$_SESSION['user_file_ext'];
$thumb_image_location = $upload_path.$thumb_image_name.$_SESSION['user_file_ext'];

//Create the upload directory with the right permissions if it doesn't exist
if(!is_dir($upload_dir)){
mkdir($upload_dir, 0777);
chmod($upload_dir, 0777);
}

//Check to see if any images with the same name already exist
if (file_exists($large_image_location)){
if(file_exists($thumb_image_location)){
$thumb_photo_exists = "<img src=\"".$upload_path.$thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail Image\"/>";
}else{
$thumb_photo_exists = "";
}
$large_photo_exists = "<img src=\"".$upload_path.$large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large Image\"/>";
} else {
$large_photo_exists = "";
$thumb_photo_exists = "";
}

if (isset($_POST["upload"])) {
//Get the file information
$userfile_name = $_FILES['image']['name'];
$userfile_tmp = $_FILES['image']['tmp_name'];
$userfile_size = $_FILES['image']['size'];
$userfile_type = $_FILES['image']['type'];
$filename = basename($_FILES['image']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));



//Only process if the file is a JPG, PNG or GIF and below the allowed limit
if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {

foreach ($allowed_image_types as $mime_type => $ext) {
//loop through the specified image types and if they match the extension then break out
//everything is ok so go and check file size
if($file_ext==$ext && $userfile_type==$mime_type){
$error = "";
break;
}else{
$error = "Solo <strong>".$image_ext."</strong> imagenes aceptadas para subir<br />";
}
}
//check if the file size is above the allowed limit
if ($userfile_size > ($max_file*1048576)) {
$error.= "Las imágenes deben estar bajo el ".$max_file."MB de tamaño";

}

}else{
$error= "Select an image for upload";
}
//Everything is ok, so we can upload the image.
if (strlen($error)==0){

if (isset($_FILES['image']['name'])){
//this file could now has an unknown file extension (we hope it's one of the ones set above!)
$large_image_location = $large_image_location.".".$file_ext;
$thumb_image_location = $thumb_image_location.".".$file_ext;

//put the file ext in the session so we know what file to look for once its uploaded
$_SESSION['user_file_ext']=".".$file_ext;

move_uploaded_file($userfile_tmp, $large_image_location);
chmod($large_image_location, 0777);

$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
//Scale the image if it is greater than the width set above
if ($height > $max_height){
$scale = $max_height/$height;
$uploaded = resizeImage($large_image_location,$width,$height,$ scale);
}else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$ scale);
}
//Delete the thumbnail file so the user can create a new one
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
}
//Refresh the page to show the new uploaded image
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
}

if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}


if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
//get the file locations
$large_image_location = $upload_path.$large_image_prefix.$_GET['t'];
$thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
header("location:".$_SERVER["PHP_SELF"]);
exit();
}



?>


<?php
rename("temp/original. aqui el formato, "temp/nuevo nombre. y el formato);

?>
  #16 (permalink)  
Antiguo 27/02/2011, 19:47
Avatar de mayid
Colaborador
 
Fecha de Ingreso: marzo-2009
Ubicación: BsAs
Mensajes: 4.014
Antigüedad: 15 años, 1 mes
Puntos: 101
Respuesta: obtener de que tipo es una imagen

Con pathinfo() podes obtener un array con : el nombre del archivo, su extension, etc. El resto es comparar la extension con los 3 o 4 tipos que admitas, o lo que necesites.
  #17 (permalink)  
Antiguo 27/02/2011, 20:00
Avatar de Marvin
Colaborador
 
Fecha de Ingreso: febrero-2005
Ubicación: global $Chile->Santiago;
Mensajes: 1.991
Antigüedad: 19 años, 2 meses
Puntos: 81
Respuesta: obtener de que tipo es una imagen

O mas facil aun... trata de implementar esto:
Código PHP:

$imagen 
"imagen.test.jpg";
$arrNombre explode('.',$imagen);
$extension $arrNombre[count($arrNombre)-1];
$arrExtPerm = array("jpg","gif","png");
$err 0;
foreach(
$arrExtPerm as $ext){
    if!(
strstr($extension,$ext)){
        
$err++;
    }    
}
if(
$err 0){
    echo 
'Foto no permitida';

O si prefieres lo pones en una funcion...
Código PHP:
if(checkExtension("imagen.test.jpg")){
    
//extension correcta
}else{
    
//extension no permitida
}

function 
checkExtension($imgName){
    
$arrNombre explode('.',$imgName);
    
$extension $arrNombre[count($arrNombre)-1];
    
$arrExtPerm = array("jpg","gif","png");
    
$err 0;
    foreach(
$arrExtPerm as $ext){
        if!(
strstr($extension,$ext)){
            
$err++;
        }    
    }
    if(
$err 0){
        return 
false;
    }else{
        return 
true;
    }

Suerte!
__________________
El que dice "Solo sé que nada sé", esta asumiendo que sabe algo.
Lea las FAQ's!

Etiquetas: tipo
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:21.