Foros del Web » Programando para Internet » PHP »

[aporte] subir y redimencionar imagen parte I

Estas en el tema de [aporte] subir y redimencionar imagen parte I en el foro de PHP en Foros del Web. buenas. hice una aplicacion para agregar datos, subir una imagen y redimencionarlo en una base de datos. El codigo de la redimencion de la imagen ...
  #1 (permalink)  
Antiguo 18/10/2009, 11:48
(Desactivado)
 
Fecha de Ingreso: junio-2009
Mensajes: 256
Antigüedad: 14 años, 10 meses
Puntos: 1
[aporte] subir y redimencionar imagen parte I

buenas. hice una aplicacion para agregar datos, subir una imagen y redimencionarlo en una base de datos. El codigo de la redimencion de la imagen lo saque de la pagina de phpclases.

http://www.phpclasses.org/browse/file/4571.html

http://www.phpclasses.org/browse/file/4582.html

script de la tabla.

Código:
CREATE TABLE `imagenes` (
  `idimagen` int(10) unsigned NOT NULL auto_increment,
  `nombres` varchar(100) NOT NULL,
  `apellidos` varchar(100) NOT NULL,
  `imagen` varchar(255) NOT NULL,
  `imagen_thb` varchar(255) NOT NULL,
  PRIMARY KEY  (`idimagen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Última edición por xfer2; 18/10/2009 a las 16:17 Razón: correcion del texto.
  #2 (permalink)  
Antiguo 18/10/2009, 11:49
(Desactivado)
 
Fecha de Ingreso: junio-2009
Mensajes: 256
Antigüedad: 14 años, 10 meses
Puntos: 1
Respuesta: [aporte] subir y redimencionar imagen parte I

parte II.

archivo conexion.php

es una simple conexion a la bd.

Código PHP:

    $cn 
= @mysql_connect("localhost","tu-usuario","clave") or die(mysql_error("Error de conexion."));
    
mysql_select_db("imagenes"); 
formulario agregar imagen.

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Subir imagenes</title>
</head>

<body>
<form action="process.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table width="378" border="0" cellpadding="0" cellspacing="2">
    <tr>
      <td width="119">Nombres</td>
      <td width="243"><input type="text" name="nombres" id="nombres" /></td>
    </tr>
    <tr>
      <td>Apellidos</td>
      <td><input type="text" name="apellidos" id="apellidos" /></td>
    </tr>
    <tr>
      <td>Imagen</td>
      <td><input type="file" name="imagen" id="imagen" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><center><input type="submit" value="Agregar imagen" />
      </center></td>
    </tr>
  </table>
</form>

</body>
</html> 
  #3 (permalink)  
Antiguo 18/10/2009, 11:50
(Desactivado)
 
Fecha de Ingreso: junio-2009
Mensajes: 256
Antigüedad: 14 años, 10 meses
Puntos: 1
Respuesta: [aporte] subir y redimencionar imagen parte I

parte III.

archivo que hace el proceso de agregar y editar imagen.

Código PHP:

    
include("includes/conexion.php");
    include(
"includes/resize.php");
    
    
$nombres $_POST['nombres'];
    
$apellidos $_POST['apellidos'];

    if(!isset(
$_POST['editar'])){
    
        
//preguntamos si el archivo imagen esta vacio
        
if (is_uploaded_file($_FILES['imagen']['tmp_name'])) {        
            
/*prefijo de cadena*/
            
$str "abcdefghijklmnopqrstuvwxyz1234567890";
            
$cad "";
            for(
$i=0;$i<12;$i++) {
                
$cad .= substr($str,rand(0,36),1);
            }         
            
#subiendo archivos al servidor 
            
$filetype $_FILES['imagen']['type'];
            
$imagen $_FILES['imagen']['name'];
            
$test explode(".",$imagen);
            
            
$size getimagesize($_FILES['imagen']['tmp_name']);//obtengo el tamaño de la imagen    
    
            //ruta del archivo
            
$path  "imagenes/"//crear la carpeta imagenes.
            
$path2 "thumbnail/"//crear la carpeta thumbnail.

                
if(strtoupper($test[1])=="JPG" || strtoupper($test[1])=="JPEG" || strtoupper($test[1])=="GIF" || strtoupper($test[1])=="PNG")
                {        
                    
$newfilename $cad.'.'.$test[1];
                    
move_uploaded_file($_FILES['imagen']['tmp_name'],$path.$newfilename); 
                    
$thb_filename "thb_".$newfilename;
                    
$thumb = new thumbnail($path.$newfilename);
                    
$thumb->size_width(172); //ancho de la imagen.
                    
$thumb->size_height(155); //alto de la imagen.
                    
$thumb->jpeg_quality(80); //calidad de imagen. es opcional.
                    
$thumb->save($path2.$thb_filename);
                    
                    
$sql  "insert into imagenes(nombres,apellidos,imagen,imagen_thb)";
                    
$sql .= "values('$nombres','$apellidos','$newfilename','$thb_filename')";
                    
                    
mysql_query($sql) or die(mysql_error());
                    
                    
header("Location:index.php");
                
                }else{
                    echo 
"<span class=form_reg_error>La imagen que intenta grabar, debe ser de formato JPG, GIF o PNG.</span>";
                    echo 
"<br />";
                    echo 
"<a href='javascript:history.back()'>&lt;&lt; Clic aqu' para regresar </a>";
                }
                
        
//Si no hay imagenes para agregar en foto usuario, procederemos a registrar los datos sin imagen:        
        
}else{
            
$nombres $_POST['nombres'];
            
$apellidos $_POST['apellidos'];
            
            
$sql  "insert into imagenes(nombres,apellidos,imagen,imagen_thb)";
            
$sql .= "values('$nombres','$apellidos','$newfilename','$thb_filename')";
            
            
header("Location:index.php");                        
        
        }
                
    }

    
#se hace el proceso de editar.
    
if(isset($_POST['editar'])){
        if(
$_POST['editar']=='1'){
                if(
$_FILES['imagen']['size'] != '0' ){ //pregunto que si el tamaño de la imagen es diferente a 0.                
                    /*prefijo de cadena*/
                    
$str "abcdefghijklmnopqrstuvwxyz1234567890";
                    
$cad "";
                    for(
$i=0;$i<12;$i++) {
                        
$cad .= substr($str,rand(0,36),1);
                    }
                                         
                    
$foto $_FILES['imagen']['name'];
                    
$test explode(".",$foto);
                    
                    
$ruta "imagenes/";
                    
$ruta_2 "thumbnail/";
                    
                        if(
strtoupper($test[1])=="JPG" || strtoupper($test[1])=="JPEG" || strtoupper($test[1])=="GIF" || strtoupper($test[1])=="PNG"){
                            
                            
$newphoto $cad.'.'.$test[1];
                            
move_uploaded_file($_FILES['imagen']['tmp_name'],$ruta.$newphoto);
                            
$thumb = new thumbnail($ruta.$newphoto);
                            
$thb_newphoto "thb_".$newphoto;
                            
$thumb->size_width(172);
                            
$thumb->size_height(155);
                            
$thumb->jpeg_quality(80);
                            
$thumb->save($ruta_2.$thb_newphoto); 
                                
                            
$sql_edit " update imagenes set nombres = '".$_POST['nombres']."',
                                           apellidos = '"
.$_POST['apellidos']."', imagen = '$newphoto',
                                           imagen_thb = '$thb_newphoto' where idimagen = '"
.$_POST['codigo']."'";
                                            
                            
mysql_query($sql_edit) or die(mysql_error());                        
                            
                        }else{
                            echo 
"<span class=form_reg_error>La imagen que intenta grabar, debe ser de formato JPG, GIF o PNG.</span>";
                            echo 
"<br />";
                            echo 
"<a href='javascript:history.back()'>&lt;&lt; Clic aqu' para regresar </a>";
                        }    
                        
                                    
//echo "con foto";
                
}else{ 
                        
//caso contrario que se mantenga los nombres de las imagenes.
                        
$newphoto $_POST['nombreFoto'];
                        
$thb_newphoto $_POST['nombreFotoThb'];
                            
//echo "sin foto".$_POST['nombreFoto'];
                            
                        
$sql_edit " update imagenes set nombres = '".$_POST['nombres']."',
                                       apellidos = '"
.$_POST['apellidos']."', imagen = '$newphoto',
                                       imagen_thb = '$thb_newphoto'
                                       where idimagen = '"
.$_POST['codigo']."'";
                                        
                        
mysql_query($sql_edit) or die(mysql_error());
                         
                        
header("Location:index.php");                            
                }    
                 

        }
    } 

Última edición por xfer2; 18/10/2009 a las 16:17 Razón: correcion del texto.
  #4 (permalink)  
Antiguo 18/10/2009, 11:52
(Desactivado)
 
Fecha de Ingreso: junio-2009
Mensajes: 256
Antigüedad: 14 años, 10 meses
Puntos: 1
Respuesta: [aporte] subir y redimencionar imagen parte I

Parte IV.

archivo donde se mostrara las imagenes agregadas.

index.php

Código PHP:

<?php 
    
include("includes/conexion.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript" type="text/javascript">
    function borrar(cod){
        con = confirm("Desea borrar la imagen");
            if(con==true){
                document.frmindex.action = "eliminar.php?cod="+cod;
                document.frmindex.submit();
            }
    }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lista imagenes</title>
</head>
<body>
<a href="agregarimagen.php">Agregar imagen</a>
<br/><br/>
<form name="frmindex" method="post">
<table border = "0" cellpadding="0" cellspacing = "0">
    <?php                
        $sql_categorias 
"SELECT * FROM imagenes";
        
$rpta_categorias mysql_query($sql_categorias) or die(mysql_error());
        
//$result = "SELECT * FROM ks_obras";
                    
        //$query = mysql_query($result) or die(mysql_error());
        
$columnes 3# Número de columnas (variable)
            
                
for ($i=1$row mysql_fetch_array($rpta_categorias); $i++) {
                    
$resto = ($i &#37; $columnes); # Número de celda del <tr> en que nos encontramos 
                        
if ($resto == 1) {
                        
    
?>
    <tr>
      <?php        
                        
# Si es la primera celda, abrimos <tr> 
      
?>
      <td width="175">
        <table border="0" cellpadding="0" cellspacing="0">
          <tr>
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr>
            <td width="155" bgcolor="#AFAFAF">
               <?php echo "Foto N° $i"?>            </td>
            <td width="11">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="2"><?=$row['nombres'].' '.$row['apellidos'];?></td>
          </tr>
          <?php
                
if($row['imagen_thb']==""){ 
                    echo 
"<tr>";
                    echo 
"<td><img src=\"images/user.jpg\" /></td>";
                    echo 
"</tr>";
                }else{
              
          
?>
          <tr>
            <td colspan="2">
                  <img src = "thumbnail/<?=$row['imagen_thb']; ?>" border="0" />            
            </td>
          </tr>
          <?php
                  
}
          
?>
          <tr>
            <td colspan="2">              
                <a href="editarimagen.php?imagen=<?=$row['idimagen']; ?>">Editar</a> | 
                    <a href="javascript:void(0);" onclick="borrar('<?=$row['idimagen']; ?>');">Borrar</a>            </td>
          </tr>
        </table>          </td>
      <?php        if ($resto == 0) {    ?>
    </tr>
    <?php            # Si es la última celda, cerramos </tr> 
                

                                
                    if (
$resto <> 0) { # Si el resultado no es múltiple de $columnes acabamos de rellenar los huecos 
                        
$ajust $columnes $resto# Número de huecos necesarios 
                            
for ($j 0$j $ajust$j++) {    
    
?>
    <tr>
      <td>&nbsp;</td>
      <?php                    }             ?>
    </tr>
    <?php
                    
# Cerramos la última línea
                                            
    
?>
</table>
</form>
<?php
        mysql_close
($cn);
?>
</body>
</html>
archivo mostrar y editar imagen.

Código PHP:

<?php
    
include("includes/conexion.php");
    
    
$sql_imagen "SELECT * FROM imagenes where idimagen = '".$_GET['imagen']."'";
    
$rpta_imagen mysql_query($sql_imagen) or die(mysql_error());
    
$fila_imagen mysql_fetch_array($rpta_imagen);
    
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Editar imagen</title>
</head>

<body>
<form action="process.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <input type = "hidden" name = "editar" id = "editar" value = "1" />
    <input type = "hidden" name = "codigo" id = "codigo" value = "<?=$_GET['imagen']; ?>" />
    <input type="hidden" name="FotoHdd" id="FotoHdd" value="<?php echo $_GET['FotoHdd'];?>" >
    <input name="nombreFoto" type="hidden" value="<?php echo $fila_imagen['imagen'];?>" />
    <input name="nombreFotoThb" type="hidden" value="<?php echo $fila_imagen['imagen_thb'];?>" />
  <table width="500" border="0" cellspacing="1" cellpadding="3">
    <tr>
      <td width="84">Nombres</td>
      <td colspan="2"><input type="text" name="nombres" id="nombres" value = "<?=$fila_imagen['nombres']; ?>" /></td>
      <td width="138" rowspan="4" valign="top"><img src = "thumbnail/<?=$fila_imagen['imagen_thb']; ?>" border="0" /></td>
    </tr>
    <tr>
      <td>Apellidos</td>
      <td colspan="2"><input type="text" name="apellidos" id="apellidos" value = "<?=$fila_imagen['apellidos']; ?>" /></td>
    </tr>
    <tr>
      <td>Subir imagen</td>
      <td colspan="2"><input type="file" name="imagen" id="imagen" /></td>
    </tr>
    
    <tr>
      <td>&nbsp;</td>
      <td width="110"><center><input type="submit" value="Editar" /></center></td>
      <td width="139"><center><input type="button" value="Cancelar" onclick="javascript:document.location.href='index.php';" /></center></td>
    </tr>
  </table>
</form>
</body>
</html>

eso es todo. si hay duda sobre la aplicacion, me lo dicen.

saludos.

Última edición por xfer2; 18/10/2009 a las 11:53 Razón: corecion del texto.
  #5 (permalink)  
Antiguo 19/10/2009, 15:10
(Desactivado)
 
Fecha de Ingreso: junio-2009
Mensajes: 256
Antigüedad: 14 años, 10 meses
Puntos: 1
Respuesta: [aporte] subir y redimencionar imagen parte I

alguna sugerencia.

saludos.
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:33.