Re: redimensionar imagen mediante librería gd

[email protected] (Carlos Medina)
Newsgroups php.general.es
Organization SimplyNetworks
Message-ID <[email protected]>
Am 20.01.2012 15:43, schrieb Omar Steffen:
> Hola amigos del foro, acudo a Uds. para ver si me pueden dar una mano,
> porque realmente estoy perdido, tengo este script que funciona bien,
> pero no se como hacer para redimensionar las imágenes, me gustaría
> trabajarlas pñor el ancho y que sea proporcional, estuve buscando en
> google, pero los ejemplos que vi no funcionaron y la verdad que estoy re
> perdido, no entiendo como puedo implementarlo en el script que tengo, se
> los pego debajo, desde ya espero me puedan dar una mano.
> Saludos a todos y que tengan un buen día
> 
> <?php
> if (!isset($_SESSION)) {
>   session_start();
> }
> $MM_authorizedUsers = "";
> $MM_donotCheckaccess = "true";
> 
> // *** Restrict Access To Page: Grant or deny access to this page
> function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
>   // For security, start by assuming the visitor is NOT authorized.
>   $isValid = False;
> 
>   // When a visitor has logged into this site, the Session variable
> MM_Username set equal to their username.
>   // Therefore, we know that a user is NOT logged in if that Session
> variable is blank.
>   if (!empty($UserName)) {
>     // Besides being logged in, you may restrict access to only certain
> users based on an ID established when they login.
>     // Parse the strings into arrays.
>     $arrUsers = Explode(",", $strUsers);
>     $arrGroups = Explode(",", $strGroups);
>     if (in_array($UserName, $arrUsers)) {
>       $isValid = true;
>     }
>     // Or, you may restrict access to only certain users based on their
> username.
>     if (in_array($UserGroup, $arrGroups)) {
>       $isValid = true;
>     }
>     if (($strUsers == "") && true) {
>       $isValid = true;
>     }
>   }
>   return $isValid;
> }
> 
> $MM_restrictGoTo = "index.php";
> if (!((isset($_SESSION['MM_Username'])) &&
> (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'],
> $_SESSION['MM_UserGroup'])))) {
>   $MM_qsChar = "?";
>   $MM_referrer = $_SERVER['PHP_SELF'];
>   if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
>   if (isset($_SERVER['QUERY_STRING']) &&
> strlen($_SERVER['QUERY_STRING']) > 0)
>   $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
>   $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" .
> urlencode($MM_referrer);
>   header("Location: ". $MM_restrictGoTo);
>   exit;
> }
> ?>
> <?php require_once('../Connections/edicion.php'); ?>
> <?php
> if (!function_exists("GetSQLValueString")) {
> function GetSQLValueString($theValue, $theType, $theDefinedValue = "",
> $theNotDefinedValue = "")
> {
>   if (PHP_VERSION < 6) {
>     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) :
> $theValue;
>   }
> 
>   $theValue = function_exists("mysql_real_escape_string") ?
> mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
> 
>   switch ($theType) {
>     case "text":
>       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
>       break;
>     case "long":
>     case "int":
>       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
>       break;
>     case "double":
>       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
>       break;
>     case "date":
>       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
>       break;
>     case "defined":
>       $theValue = ($theValue != "") ? $theDefinedValue :
> $theNotDefinedValue;
>       break;
>   }
>   return $theValue;
> }
> }
> 
> $editFormAction = $_SERVER['PHP_SELF'];
> if (isset($_SERVER['QUERY_STRING'])) {
>   $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
> }
> 
> if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
> 
>         //Variable para saber si se produce algun error
>        $error=0;
>         // Guarda las caracteristicas de la imagen
>         $directorio = "../imagenes/tapa/"; //$directorio = al directorio
> donde se guarda la foto
> 
>         $prefijo = time(); //$prefijo= al numero que se le adiciona al
> nombre que tiene la foto para que sea único
> 
>         //$file==al prefijo (parte que se adiciona al nombre original) y
> al nombre con el que se guarde la foto
>         $file= $prefijo.$_FILES['imagen']['name'];
>         //tipo_archivo= a la extension del archivo que acepto en las
> imagenes (jpg, gif y png)
>         $tipo_archivo = $_FILES['imagen']['type'];
>         // tamano_archivo= Almacena el tamaño del archivo en bytes
>         $tamano_archivo = $_FILES['imagen']['size'];
>         //compruebo si las características del archivo son las que deseo
>         if($nombre_archivo!=$directorio){
>         if (!((strpos($tipo_archivo, "gif") || strpos($tipo_archivo,
> "jpeg") || strpos($tipo_archivo, "png")) && ($tamano_archivo < 2000000))) {
>           //el tamaño o la extension del archivo no son correctas se
> pone error=1
>           $error=1;
> 
>         }else{
> 
>         if (@copy($_FILES['imagen']['tmp_name'], $directorio.$file)){
>          // El archivo ha sido cargado con éxito
> 
>         }else{
>         //No se ha podido guardar el archivo en el servidor error=2
>         $error=2;
>          }
>        }
>        }
>            // Comprueba si tiene algun error
>                if ($error==1){
>             echo "<script> alert ( \"El archivo no debe tener un tamaño
> superior a 200 KB y deber ser JPG, PNG o GIF\"); </script>";
>             echo "<script language=Javascript>
> location.href=\"p_tapa.php\" ; </script>";
>             die(); }
>             elseif ($error==2){
>             echo "<script> alert (\"No se ha podido guardar la imagen en
> el SERVIDOR \"); </script>";
> 
>             die();
>             }
>             //si no hay errores se inserta en la TABLA
>             else{
>  }
> 
> 
> 
> 
> 
>   $insertSQL = sprintf("INSERT INTO tapa (idtapa, fecha, imagen) VALUES
> (%s, %s, %s)",
>                        GetSQLValueString($_POST['idtapa'], "int"),
>                        GetSQLValueString($_POST['fecha'], "date"),
>                        GetSQLValueString($file,"text")
>                        );
> 
> 
> 
>   mysql_select_db($database_edicion, $edicion);
>   $Result1 = mysql_query($insertSQL, $edicion) or die(mysql_error());
> 
>   $insertGoTo = "p_tapa.php";
>   if (isset($_SERVER['QUERY_STRING'])) {
>     $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
>     $insertGoTo .= $_SERVER['QUERY_STRING'];
>   }
>   header(sprintf("Location: %s", $insertGoTo));
> }
> 
> mysql_select_db($database_edicion, $edicion);
> $query_ctapa = "SELECT * FROM tapa";
> $ctapa = mysql_query($query_ctapa, $edicion) or die(mysql_error());
> $row_ctapa = mysql_fetch_assoc($ctapa);
> $totalRows_ctapa = mysql_num_rows($ctapa);
> ?>
> <html><!-- #BeginTemplate "/Templates/formulario.dwt" --><!-- DW6 -->
> <head>
> <!-- #BeginEditable "doctitle" -->
> <title>Untitled Document</title>
> <!-- #EndEditable -->
> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
> <link rel="stylesheet" href="estilos.css" type="text/css">
> <script type="text/javascript" src="datepickercontrol.js"></script>
> <script language="JavaScript">
>      if (navigator.platform.toString().toLowerCase().indexOf("linux") !=
> -1){
>          document.write('<link type="text/css" rel="stylesheet"
> href="datepickercontrol_lnx.css">');
>      }
>      else{
>          document.write('<link type="text/css" rel="stylesheet"
> href="datepickercontrol.css">');
>      }
> </script>
> <script
> src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
> type="text/javascript"></script>
> <script
> src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
> 
> <link rel="stylesheet" href="jquery-ui.css" type="text/css" />
> <script src="jquery.easy-confirm-dialog.js"></script>
> <script type="text/javascript">
>     $(function() {
>         $(".confirm").easyconfirm();
>     $("#alert").click(function() {
> 
>     });
> 
>     });
> </script>
> 
> <style type="text/css">
>     .ui-dialog { font-size: 12px; }
> </style>
> <script type="text/javascript">
>             function preview (campo) {
>                 campo = document.getElementById('file').value;
>                 alert("Antes: "+campo);
>                 //imagen = document.getElementById('previsualizacion');
>                 //ruta = 'file:///'+ campo;
>                 //ruta = escape(ruta);
>                 //ruta = ruta.replace(/%5C/g, "/");
>                 //ruta = ruta.replace(/%3A/g, ":");
>                 alert("Despues: "+ruta);
>                 //imagen.src = ruta;
>                 //imagen.style.display = 'block';
>                 imagen.style.width = "200px";
>                 imagen.style.height = "150px";
>             }
> </script>
> 
> </head>
> 
> <body bgcolor="#FEF4F3" text="#000000">
> 
> <table width="100%" border="0" cellspacing="0" cellpadding="0">
> <tr>
> <td valign="top"> <!-- #BeginEditable "editable" -->
> <?php
> setlocale(LC_TIME,'es_ES');
> $fecha=strftime("%Y-%m-%d");
> ?>
> <table width="97%" border="0" align="center">
> <tr>
> <td><strong><span class="titulo">Cargar Foto de Tapa<br>
> <br>
> </span></strong></td>
> </tr>
> <tr>
> <td valign="top">
> <form action="<?php echo $editFormAction; ?>" method="post"
> enctype="multipart/form-data" name="form1">
> <table width="100%" border="0" align="center" cellpadding="0"
> cellspacing="0" class="borde_tabla">
> <tr valign="baseline">
> <td width="15%" align="right" nowrap bgcolor="#FFFFFF"
> class="nota">&nbsp;</td>
> <td colspan="2" bgcolor="#FFFFFF"><input name="hiddenField"
> type="hidden" id="hiddenField" value="<?php echo $row_ctapa['idtapa'];
> ?>"></td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF" class="nota">&nbsp;Fecha:</td>
> <td colspan="2" bgcolor="#FFFFFF"><input type="hidden"
> id="DPC_CALENDAR_OFFSET_X" value="20">
> <input type="hidden" id="DPC_BUTTON_OFFSET_X" value="10">
> <input type="text" id="DPC_calendar1b_YYYY-MM-DD" name="fecha"
> size="10"></td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF" class="nota">&nbsp;</td>
> <td colspan="2" bgcolor="#FFFFFF">&nbsp;</td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF" class="nota">&nbsp;Imagen de
> Tapa</td>
> <td colspan="2" bgcolor="#FFFFFF"><input name="imagen" type="file"
> id="imagen" value="imagen" size="32"></td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF">&nbsp;</td>
> <td colspan="2" bgcolor="#FFFFFF">&nbsp;</td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF">&nbsp;</td>
> <td width="28%" bgcolor="#FFFFFF"><input type="submit" value="Insertar
> registro"></td>
> <td width="57%" bgcolor="#FFFFFF"><input type="reset" name="borrar"
> value ="Borrar Datos"></td>
> </tr>
> <tr valign="baseline">
> <td align="right" nowrap bgcolor="#FFFFFF">&nbsp;</td>
> <td colspan="2" bgcolor="#FFFFFF">&nbsp;</td>
> </tr>
> </table>
> <input type="hidden" name="MM_insert" value="form1">
> </form>
> </td>
> </tr>
> </table>
> <!-- #EndEditable --> </td>
> </tr>
> </table>
> 
> </body>
> <!-- #EndTemplate --></html>
> <?php
> mysql_free_result($ctapa);
> ?>
> 



Hola:

<?php

class Image
{
    private $p      = null; // Percentage
    private $width  = null;
    private $height = null;
    private $size   = null;
    private $type   = null;
    private $mime   = null;
    private $sImage = null;

    public function __construct( $imagePath )
    {
        try
        {
            $image      = getimagesize( $imagePath );
            $this->size = array( $image[0], $image[1] );
            $this->mime = $image['mime'];
            $tmp        = explode( "/", $image['mime'] );
            $this->type = strtoupper( $tmp[1] );
            $this->imageCreate( $imagePath );
        }
        catch( Exception $e )
        {
            throw $e;
        }
    }

    /**
    * create the source image to resize
    *
    * @param mixed $imagePath
    */
    public function imageCreate( $imagePath = null, $object = null )
    {
        if( !$imagePath && $object == null )
        {
            throw new Exception( "Please provide the Image Path" );
        }

        try
        {
            switch( $this->type )
            {
                case 'GIF':
                    $this->sImage = ( isset($imagePath) )?
imagecreatefromgif( $imagePath ):imagegif( $object );
                    break;
                case 'JPEG':
                    $this->sImage = ( isset($imagePath) )?
imagecreatefromjpeg( $imagePath ):imagejpeg( $object );
                    break;
                case 'PNG':
                    $this->sImage = ( isset($imagePath) )?
imagecreatefrompng( $imagePath ):imagepng( $object );
                    break;
            }
        }
        catch( Exception $e )
        {
            throw $e;
        }
    }

    public function resizeImage( $target )
    {
        try
        {
            $this->calculateResize( $target );
        }
        catch( Exception $e )
        {
            throw $e;
        }

        try
        {
            // evaluate to create here method to construct other images
            $image = imagecreatetruecolor( $this->width, $this->height );
            imagecopyresized($image, $this->sImage, 0, 0, 0, 0,
$this->width, $this->height, $this->size[0], $this->size[1]);
            header('Content-Type: ' . $this->mime );
            $this->imageCreate( null, $image );
        }
        catch( Exception $e )
        {
            throw $e;
        }
    }

    /**
    * Calculate resizing
    *
    * @param mixed $target
    * @param mixed $width
    * @param mixed $height
    * return void
    */
    private function calculateResize( $target, $width = null, $height =
null )
    {
        $this->width    = ( isset( $width )) ? $width: $this->size[0];

        $this->height   = ( isset( $height )) ? $height: $this->size[1];

        try
        {
            if( $this->width > $this->height ){
                $this->p = ( $target / $this->width );
            }
            else
            {
                $this->p = ( $target / $this->height );
            }
        }
        catch( Exception $e )
        {
            throw $e;
        }

        try
        {
            $this->width    = round(  $this->width * $this->p );
            $this->height   = round(  $this->height * $this->p );
        }
        catch( Exception $e )
        {
            throw $e;
        }
        return null;
    }
}


$imageGif = "/var/www/imagegif.gif";

$i = new Image( $imageGif );
$i->resizeImage( 100 );


De pronto y te ayuda


Carlos Medina
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.