Foros del Web » Programando para Internet » PHP »

Aporte: Upload n Imagenes (redimensionadas) con Thumbnails (crop)

Estas en el tema de Aporte: Upload n Imagenes (redimensionadas) con Thumbnails (crop) en el foro de PHP en Foros del Web. Hola, que tal? Estuve trabajando en esto los ultimo dias y he podido lograr hacer para que mi codigo funcione para que uno pueda elegir ...
  #1 (permalink)  
Antiguo 19/09/2011, 16:10
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 8 meses
Puntos: 8
Aporte: Upload n Imagenes (redimensionadas) con Thumbnails (crop)

Hola, que tal?

Estuve trabajando en esto los ultimo dias y he podido lograr hacer para que mi codigo funcione para que uno pueda elegir la cantidad de fotos a subir, una vez que esten subidas, seleccionas en la foto que parte quieres que sea el thumbnail, se hace un crop y guarda el thumbnail tambien para cada foto.

Espero que pueda servirle a alguien.

Solo tiene un problema, el peso total de las fotos a subir no pueden exceder los 7 megas. Nose como solucionar esto, si identifica ese error, seria formidable.

seleccionar_cantidad_imagenes.php
Código 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>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
head>
</
head>
<
body>
<
form method="post" action="elegir_imagenes.php">
  <
table border="0">
  <
tr>
    <
td align="right">Cantidad de Imagenes: </td>
    <
td>
        <
select name="imagenes" >
            <
option value="1">1</option>
            <
option value="2">2</option>
            <
option value="3">3</option>
            <
option value="4">4</option>
            <
option value="5">5</option>
        </
select>
    </
td>
    <
td></td>
  </
tr>
  <
tr>
    <
td align="right"></td>
    <
td>
    <
input name="continuar" type="submit" value="Continuar" />
    </
td>
  </
tr>
  </
table>
</
form>
</
body>
</
html
elegir_imagenes.php
Código 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Subir Foto</h2>
    <form name="photo" enctype="multipart/form-data" action="subir_imagenes.php" method="post">
    <?php
    $cantidad
=$_POST['imagenes'];
    for(
$i=1;$i<=$cantidad;$i++){
        echo 
"Foto <input type='file' name='image".$i."' size='30' /><br>";
    }
    
?>
    <input type="hidden" name="imagenes" value="<?php echo $cantidad?>">
    <input type="submit" name="upload" value="Upload" />
    </form>
</body>
</html>
continua...
  #2 (permalink)  
Antiguo 19/09/2011, 16:12
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 8 meses
Puntos: 8
Respuesta: Aporte: Upload n Imagenes (redimensionadas) con Thumbnails (crop)

subir_imagenes.php
Código PHP:
<?php
error_reporting 
(E_ALL E_NOTICE);
session_start();

$cantidad=$_POST['imagenes'];

for(
$i=1;$i<=$cantidad;$i++){
$random_key[$i] = strtotime(date('Y-m-d H:i:s'))."_".$i;
$user_file_ext[$i] = "";
}

$upload_dir "Imagenes_Productos";
$upload_path $upload_dir."/";

$large_image_prefix "resize_";
$thumb_image_prefix "thumbnail_";

for(
$i=1;$i<=$cantidad;$i++){
$large_image_name[$i] = $large_image_prefix.$random_key[$i];
$thumb_image_name[$i] = $thumb_image_prefix.$random_key[$i];
}
$max_file "4";
$max_width "900";
$max_height "710";
$thumb_width "80";
$thumb_height "80";
$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);
$image_ext "";
foreach (
$allowed_image_ext as $mime_type => $ext) {
    
$image_ext.= strtoupper($ext)." ";
}
for(
$i=1;$i<=$cantidad;$i++){
$large_image_location[$i] = $upload_path.$large_image_name[$i].$user_file_ext[$i];
$thumb_image_location[$i] = $upload_path.$thumb_image_name[$i].$user_file_ext[$i];
}

if(!
is_dir($upload_dir)){
    
mkdir($upload_dir0777);
    
chmod($upload_dir0777);
}

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,$newImageHeight);
    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,$newImageWidth,$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($image0777);
    return 
$image;
}
function 
getHeight($image) {
    
$size getimagesize($image);
    
$height $size[1];
    return 
$height;
}
function 
getWidth($image) {
    
$size getimagesize($image);
    
$width $size[0];
    return 
$width;
}


for(
$i=1;$i<=$cantidad;$i++){
    
$userfile_name[$i] = $_FILES['image'.$i]['name'];
    
$userfile_tmp[$i] = $_FILES['image'.$i]['tmp_name'];
    
$userfile_size[$i] = $_FILES['image'.$i]['size'];
    
$userfile_type[$i] = $_FILES['image'.$i]['type'];
    
$filename[$i] = basename($_FILES['image'.$i]['name']);
    
$file_ext[$i] = strtolower(substr($filename[$i], strrpos($filename[$i], '.') + 1));
    if((!empty(
$_FILES["image".$i])) && ($_FILES['image'.$i]['error'] == 0)) {
        foreach (
$allowed_image_types as $mime_type => $ext) {
            if(
$file_ext[$i]==$ext && $userfile_type[$i]==$mime_type){
                
$error "";
                break;
            }else{
                
$error "Solo <strong>".$image_ext."</strong> imagenes son aceptadas<br />";
            }
        }
        if (
$userfile_size[$i] > ($max_file*1048576)) {
            
$error.= "Las imagenes deben pesar menos de ".$max_file."MB";
        }
    }else{
        
$error"Elige una imagen para subir";
    }
    if (
strlen($error)==0){
        
        if (isset(
$_FILES['image'.$i]['name'])){
            
$large_image_location[$i] = $large_image_location[$i].".".$file_ext[$i];
            
$thumb_image_location[$i] = $thumb_image_location[$i].".".$file_ext[$i];
            
$user_file_ext[$i]=".".$file_ext[$i];
            
move_uploaded_file($userfile_tmp[$i], $large_image_location[$i]);
            
chmod($large_image_location[$i], 0777);
            
$width getWidth($large_image_location[$i]);
            
$height getHeight($large_image_location[$i]);
            if (
$width $height){
                if (
$width $max_width){
                    
$scale $max_width/$width;
                    
$uploaded resizeImage($large_image_location[$i],$width,$height,$scale);
                }else{
                    
$scale 1;
                    
$uploaded resizeImage($large_image_location[$i],$width,$height,$scale);
            }
            }else{
                if (
$height $max_height){
                    
$scale $max_height/$height;
                    
$uploaded resizeImage($large_image_location[$i],$width,$height,$scale);
                }else{
                    
$scale 1;
                    
$uploaded resizeImage($large_image_location[$i],$width,$height,$scale);
            }
            }
        }
    }
}

for(
$i=1;$i<=$cantidad;$i++){
    if (
file_exists($large_image_location[$i])){
        
$large_photo_exists[$i] = "<img src='".$upload_path.$large_image_name[$i].$user_file_ext[$i]."'>";
    } else {
        
$large_photo_exists[$i] = "";
    }
}
for(
$i=1;$i<=$cantidad;$i++){
    
$current_large_image_width[$i] = getWidth($large_image_location[$i]);
    
$current_large_image_height[$i] = getHeight($large_image_location[$i]);
}
?>



<!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" />
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>
<script type="text/javascript">
<?php
for($i=1;$i<=$cantidad;$i++){ ?>
function preview<?php echo $i?>(img, selection) { 
    var scaleX = <?php echo $thumb_width;?> / selection.width; 
    var scaleY = <?php echo $thumb_height;?> / selection.height; 
    
    $('#thumbnail<?php echo $i?> + div > img').css({ 
        width: Math.round(scaleX * <?php echo $current_large_image_width[$i];?>) + 'px', 
        height: Math.round(scaleY * <?php echo $current_large_image_height[$i];?>) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
    });
    $('#x1_<?php echo $i?>').val(selection.x1);
    $('#y1_<?php echo $i?>').val(selection.y1);
    $('#x2_<?php echo $i?>').val(selection.x2);
    $('#y2_<?php echo $i?>').val(selection.y2);
    $('#w_<?php echo $i?>').val(selection.width);
    $('#h_<?php echo $i?>').val(selection.height);

<?php ?>
$(document).ready(function () { 
    $('#save_thumb').click(function() {
        <?php for($i=1;$i<=$cantidad;$i++){?>
        var x1<?php echo $i?> = $('#x1_<?php echo $i?>').val();
        var y1<?php echo $i?> = $('#y1_<?php echo $i?>').val();
        var x2<?php echo $i?> = $('#x2_<?php echo $i?>').val();
        var y2<?php echo $i?> = $('#y2_<?php echo $i?>').val();
        var w<?php echo $i?> = $('#w_<?php echo $i?>').val();
        var h<?php echo $i?> = $('#h_<?php echo $i?>').val();
        <?php ?>
        <?php for($i=1;$i<=$cantidad;$i++){?>
        if(x1<?php echo $i?>=="" || y1<?php echo $i?>=="" || x2<?php echo $i?>=="" || y2<?php echo $i?>=="" || w<?php echo $i?>=="" || h<?php echo $i?>==""){
            alert("Debes seleccionar el thumbnail de la imagen: <?php echo $i?>");
            return false;
        }
        <?php ?>    
        return true;
    });
}); 

$(window).load(function () { 
    <?php for($i=1;$i<=$cantidad;$i++){?>
    $('#thumbnail<?php echo $i?>').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview<?php echo $i?> }); 
    <?php ?>
});

</script>


<title></title>
</head>

<body>
<form name="thumbnail" action="subir_thumbnails.php" method="post">
<?php
for($i=1;$i<=$cantidad;$i++){
        echo     
"<div><img style='float:left;' src='".$upload_path.$large_image_name[$i].$user_file_ext[$i]."' id='thumbnail".$i."'>"
                
."<div style='border:1px #e5e5e5 solid; float:left; overflow:hidden; width:".$thumb_width."px; height:".$thumb_height."px;'>"
                
."<img src='".$upload_path.$large_image_name[$i].$user_file_ext[$i]."' style='position: relative;' alt='Thumbnail Preview' /></div><br style='clear:both;'/>"
                
."<input type='hidden' name='x1_".$i."' value='' id='x1_".$i."' />"
                
."<input type='hidden' name='y1_".$i."' value='' id='y1_".$i."' />"
                
."<input type='hidden' name='x2_".$i."' value='' id='x2_".$i."' />"
                
."<input type='hidden' name='y2_".$i."' value='' id='y2_".$i."' />"
                
."<input type='hidden' name='w_".$i."' value='' id='w_".$i."' />"
                
."<input type='hidden' name='h_".$i."' value='' id='h_".$i."' />"
                
."<input type='hidden' name='thumb_image_location".$i."' value='".$thumb_image_location[$i]."'  />"
                
."<input type='hidden' name='large_image_location".$i."' value='".$large_image_location[$i]."'  /></div>";
}
?>
<input type='hidden' name='imagenes' value='<?php echo $cantidad?>' />
<input type="submit" name="upload_thumbnail" value="Save Thumbnail" id="save_thumb" />
</form>
</body>
</html>
continua...
  #3 (permalink)  
Antiguo 19/09/2011, 16:15
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 8 meses
Puntos: 8
Respuesta: Aporte: Upload n Imagenes (redimensionadas) con Thumbnails (crop)

subir_thumbnails.php
Código PHP:
<?php
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,$newImageHeight);
    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_width,$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_name0777);
    return 
$thumb_image_name;
}
$thumb_width "80";
$cantidad=$_POST['imagenes'];
for(
$i=1;$i<=$cantidad;$i++){
$x1[$i]=$_POST['x1_'.$i];
$y1[$i]=$_POST['y1_'.$i];
$x2[$i]=$_POST['x2_'.$i];
$y2[$i]=$_POST['y2_'.$i];
$w[$i]=$_POST['w_'.$i];
$h[$i]=$_POST['h_'.$i];
$scale[$i] = $thumb_width/$w[$i];
$thumb_image_location[$i]=$_POST['thumb_image_location'.$i];
$large_image_location[$i]=$_POST['large_image_location'.$i];
$cropped=resizeThumbnailImage($thumb_image_location[$i], $large_image_location[$i],$w[$i],$h[$i],$x1[$i],$y1[$i],$scale[$i]);
}
echo 
"Las imagenes y sus thumbnails han sido subido con exito."
?>
El codigo lo saque de esta pagina: [URL="http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop-v11/"]aqui[/URL].
El jquery-1.4.3.min.js lo pueden descargar de ese mismo link, asi como el jquery.imgareaselect.min.js.

Espero que les funcione bien, pueden editarlo para poder usar base de datos y todo, es bien facil de entender.

Saludos

Última edición por morfasto; 19/09/2011 a las 16:21

Etiquetas: html, imagenes, thumbnails, upload
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.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 04:52.