Les traigo un pequeño proyecto que ya tiene su tiempo, que lo que hace es crear galerías, y dentro de cada galería uno puede subir la cantidad de imágenes que desee, y agregarle un par de datos como Titulo de la foto, Nombre de la Galería, fecha.
Esta realizado en php con algo de JavaScripts.
Sepan disculpar el POO fue uno de mis primeros proyectos, diseñado así que seguramente tiene muchos errores.
Primero el archivo index.php
Ahora el archivo listado, que lo que nos muestra es una lista de las galerías que hemos creado :
Y ahora el que se encarga de subir más imágenes a la galería que se ha elegido:
La clase subirarchivo.class.php que es la que se encarga de la suba de las imágenes, y limpiar el nombre de los archivos y un par de cosas más.
Y por ultimo la clase imglib.class.php que es una clase prediseñada creo que no tiene muchos arreglos por mi parte. Esta se encarga de el diseño de la imagen, sirve para re dimensionar si uno quiere la imagen.
Como pueden ver, las imagenes se guarda en 3 dimensiones, la primera es tal cual la original, y las otras dos son las dimesiones que lee de una tabla Mysql llamada tamano, donde en mi caso le puse dos medidas, una media y otra pequeña.
El diseño de las BD es el siguiente :
También les dejo todos los archivos para que lo puedan descargar, los único que les quedaría es crear las tablas que para mayor comodidad esta el archivo .sql.
Saludos y espero que les sea útil.
Esta realizado en php con algo de JavaScripts.
Sepan disculpar el POO fue uno de mis primeros proyectos, diseñado así que seguramente tiene muchos errores.
Primero el archivo index.php
<?php
include("config/conf_mysql.php");
include("php/conexbd.class.php");
include("php/varios.class.php");
//fotos
include("php/subirarchivo.class.php");
include("php/imglib.class.php");
include("php/archivo.class.php");
$dirgaleria="upload/";
//fotos
include("php/fotos.class.php");
if ( isset($_POST["aceptar"])) { //if guardar
// Guardar la foto
$v=new Varios();
$guarda[0]=trim(($_POST["galeria"]));
$guarda[1]=$v->FormatoFechaMysql($_POST["fecha"]);
$guarda[2]=trim($_POST["titulo"]);
$guarda[3]=trim($_POST["descripcion"]);
$guarda[6]=$_POST["enlace"];
if (isset($_POST["aceptar"]) && (count($_FILES) > 0)){
$sa=new SubirArchivo();
$sa->GuardarExtension($config["up_extvalida"]);
$sa->CrearDestinoSiNoExiste(false);
$guarda[4]=$sa->fixFileName($guarda[0]);// limpio el nombre para la galeria
$dirgaleria.= $guarda[4].'/';
$guarda[5]=$sa->fixFileName($guarda[2]);// limpio el titulo para el nombre
//Veo si la galeria ya existe
$b=new Fotos();
$b->UsarMysql();
$b->DefinirDatosConex($config["mysql_host"], $config["mysql_bd"], $config["mysql_usuario"], $config["mysql_clave"]);
$existe=$b->ExisteGaleria($guarda[4]);
if(count($existe)>0){
$error1= "la galería ya existe, cambie el nombre";
}else{
$sa->CreaCarpeta($dirgaleria);
$error1=trim($sa->VerError());
if ($error1 == ""){
move_uploaded_file($_FILES['imagen']["tmp_name"],$dirgaleria.$guarda[5].'.jpg');
//Traigo los tamaños que voy a utilizar desde la bd
$tamano=$b->Tamanos();
//
if(isset($tamano)) foreach($tamano as $ind=>$tam){
$a=new Archivo();
$img = new imglib($dirgaleria.$guarda[5].'.jpg');
$img->width = $tam['ancho'];
$img->height =$tam['largo'];
$img->reSize();
$img->save('JPEG',$dirgaleria.$guarda[5].'_'.$tam['tipo'].'.jpg');
}
}//fin if
$guarda[8] =$dirgaleria.$guarda[5]; // direcc foto
//Guarda Galeria
$b->GuardaGaleria($guarda);
$retorno=$b->LeerError();
//leo el id de la galeria para relacionarlo con la foto
$id=$b->LeeIdGaleria();
$retorno=$b->LeerError();
$guarda[7]=$id[0]['id'];//id de la galeria
$b->GuardaFoto($guarda);
$retorno=$b->LeerError();
}
}//fin guardar foto
}//if guardar
?>
<!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=iso-8859-1" />
<title>Fotos</title>
<script language="javascript" type="text/javascript" src="js/validar.js"> </script>
<script src="js/fecha.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/base.css" type="text/css" />
<link rel="stylesheet" href="css/form.css" type="text/css" />
</head>
<body>
<div id="dcentral">
<form id="form1" name="form1" action="<?php echo $_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" onSubmit="return valida(this);" >
<fieldset>
<legend>Galeria</legend>
<label class="titcampo">Nombre Galería:</label><br />
<input type="text" name="galeria" id="galeria" size="30" value="" /><br />
<label class="titcampo">Fecha</label> <br />
<input name="fecha" type="text" size="10" maxlength="10" onKeyUp = "this.value=formateafecha(this.value);"> <br />
<label class="titcampo">Foto:</label><br />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="imagen" id="imagen" size="35" /><br />
<label class="titcampo">Titulo :</label><br />
<input type="text" name="titulo" id="titulo" size="30" value="" /><br />
<label class="titcampo">Enclace :</label><br />
<input type="text" name="enlace" id="enlace" size="50" value="" /><br />
<label class="titcampo">Descripción :</label><br />
<textarea name="descripcion" rows="7" cols="90"></textarea><br />
<input type="submit" name="aceptar" id="aceptar" value="Guardar" />
</fieldset>
</form>
</div>
<?php
if ($error1<>""){
echo "<p class="error">".$error1."</p>";
}else{
echo "<p class="listo">Los datos se guardaron correctamente</p>";
}
?>
</div>
</body>
</html>
Ahora el archivo listado, que lo que nos muestra es una lista de las galerías que hemos creado :
<?php
include("config/conf_mysql.php");
include("php/conexbd.class.php");
include("php/varios.class.php");
include("php/fotos.class.php");
// Leo las galerias
$c=new Fotos();
$c->UsarMysql();
$c->DefinirDatosConex($config["mysql_host"], $config["mysql_bd"], $config["mysql_usuario"], $config["mysql_clave"]);
$galerias=$c->LeeGaleria();
?>
<!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=iso-8859-1" />
<title>Listado</title>
<link rel="stylesheet" href="css/base.css" type="text/css" />
<link rel="stylesheet" href="css/tabla.css" type="text/css" />
<link rel="stylesheet" href="css/form.css" type="text/css" />
</head>
<body>
<div id="dcentral">
<table class="clstabla">
<tr>
<th>Nombre</th>
<th>Foto</th>
</tr>
<?php
if(isset($galerias)) foreach($galerias as $ind=>$dato){
?>
<tr>
<td><a href="carga_fotos.php?id=<?= $dato['id_galeria']?>"><?=$dato['nombre']?></a></td>
<td><a href="carga_fotos.php?id=<?= $dato['id_galeria']?>"><img src="<?=$dato['foto'].'_chico.jpg'?>" width="50px" height="50px" /> </a></td>
</tr>
<?}?>
</table>
</div>
</body>
</html>
Y ahora el que se encarga de subir más imágenes a la galería que se ha elegido:
<?php
if(isset($_GET['id'])){
include("config/conf_mysql.php");
include("php/conexbd.class.php");
include("php/varios.class.php");
include("php/fotos.class.php");
//fotos
include("php/subirarchivo.class.php");
include("php/imglib.class.php");
include("php/archivo.class.php");
$dirgaleria="upload/";
//fotos
if(isset($_GET["eliminar"])){
$eliminar=$_GET["eliminar"];
$e=new Fotos();
$e->UsarMysql();
$e->DefinirDatosConex($config["mysql_host"], $config["mysql_bd"], $config["mysql_usuario"], $config["mysql_clave"]);
$e->BorrarFoto($eliminar);
$e->CerrarConex();
$retorno=$e->LeerError();
}
// Leo el nombre de la galeria donde se guardaran las fotos
$b=new Fotos();
$b->UsarMysql();
$b->DefinirDatosConex($config["mysql_host"], $config["mysql_bd"], $config["mysql_usuario"], $config["mysql_clave"]);
$galeria=$b->LeeNombreGaleria($_GET['id']);
if(isset($_POST["aceptar"])){
$v=new Varios();
$guarda[0]=$v->FormatoFechaMysql($_POST["fecha"]);
$guarda[1]=trim($_POST["titulo"]);
$guarda[2]=trim($_POST["descripcion"]);
$guarda[3]=$_POST["enlace"];
if (isset($_POST["aceptar"]) && ($_FILES['imagen']["tmp_name"]<>"")){
$error1="";
$error2="";
$sa=new SubirArchivo();
$sa->GuardarExtension($config["up_extvalida"]);
$sa->CrearDestinoSiNoExiste(false);
$dirgaleria.= $galeria[0]['nombre_real'].'/';
$guarda[4]=$sa->fixFileName($guarda[1]);// limpio el titulo para el nombre
// $sa->CreaCarpeta($dirgaleria);
$error1=trim($sa->VerError());
if ($error1 == ""){
move_uploaded_file($_FILES['imagen']["tmp_name"],$dirgaleria.$guarda[4].'.jpg');
//Traigo los tamaños que voy a utilizar desde la bd
$tamano=$b->Tamanos();
//
if(isset($tamano)) foreach($tamano as $ind=>$tam){
$a=new Archivo();
$img = new imglib($dirgaleria.$guarda[4].'.jpg');
$img->width = $tam['ancho'];
$img->height =$tam['largo'];
$img->reSize();
$img->save('JPEG',$dirgaleria.$guarda[4].'_'.$tam['tipo'].'.jpg');
}
}//fin if
$guarda[5] =$dirgaleria.$guarda[4]; // direcc foto
$guarda[6]=$_GET['id'];// id de la galeria
//Guardo Foto
$b->GuardaFotoNueva($guarda);
$retorno=$b->LeerError();
}//fin guardar foto
}
// Leo las galerias
$fotos=$b->LeeFotos($_GET['id']);
}else{
header('refresh:2; url=listado.php');
echo ' No ha ingresado ningúna galería, por favor elija en cual desea cargar imagenes.';
}
?>
<!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=iso-8859-1" />
<title>Listado</title>
<script language="javascript" type="text/javascript" src="js/validar.js"> </script>
<script src="js/fecha.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/base.css" type="text/css" />
<link rel="stylesheet" href="css/tabla.css" type="text/css" />
<link rel="stylesheet" href="css/form.css" type="text/css" />
<script>
function confirmar()
{
if(confirm('¿Esta seguro de eliminar la fotografía?'))
return true;
else
return false;
}
</script>
</head>
<body>
<form id="form1" name="form1" action="carga_fotos.php?id=<?=$_GET['id']?>" method="post" enctype="multipart/form-data" onSubmit="return validafoto(this);">
<fieldset>
<legend>Fotos de la Galería</legend>
<div id="div_foto" style="width:500px">
<?php
if(isset($fotos)) foreach($fotos as $foto){
?>
<div style="float:left; padding:5px;"><img src="<?=$foto['nombre'].'_chico.jpg'?>" width="70" height="70" /><br/>
<a href="carga_fotos.php?id=<?=$_GET['id']?>&eliminar=<?=$foto['id_foto']?>" onclick="return confirmar()"><img src="images/delete.gif"
alt="Editar" border="0" title="Eliminar dato" /></a><br />
</div>
<?}?>
</div>
</fieldset>
<fieldset>
<legend> Cargar nueva Foto</legend>
<label class="titcampo">Fecha</label> <br />
<input name="fecha" type="text" size="10" maxlength="10" onKeyUp = "this.value=formateafecha(this.value);"> <br />
<label class="titcampo">Foto:</label><br />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="imagen" id="imagen" size="35" /><br />
<label class="titcampo">Titulo :</label><br />
<input type="text" name="titulo" id="titulo" size="30" value="" /><br />
<label class="titcampo">Enclace :</label><br />
<input type="text" name="enlace" id="enlace" size="50" value="" /><br />
<label class="titcampo">Descripción :</label><br />
<textarea name="descripcion" rows="7" cols="90"></textarea><br />
<input type="submit" name="aceptar" id="aceptar" value="Guardar" />
</fieldset>
</form>
<div id="dcentral">
</div>
</body>
</html>
La clase subirarchivo.class.php que es la que se encarga de la suba de las imágenes, y limpiar el nombre de los archivos y un par de cosas más.
<?php
class SubirArchivo {
//Propiedades
var $error;//tipo: string
var $extension;//tipo: string
var $rutadestino;//tipo: string
var $nomcampo;//tipo: string
var $crearutadestino;//tipo boolean
//Metodos
function SubirArchivo(){
ini_set('max_execution_time', '180');//tiempo maximo para ejecucion del script
$this->error="";
$this->extension="*";
$this->rutadestino="./";
$this->nomcampo="";
$this->crearutadestino=false;
}
function GuardarExtension($extension){
if (trim($extension)!=""){
$this->extension=strtolower(str_replace(" ", "", $extension));
//if (strpos($this->extension,".")==false) $this->extension=(".".$this->extension);
}else{
$this->extension="*";
}
}
function CreaCarpeta($destino){
if (!file_exists($destino)){
if(!mkdir($destino)){
$this->error="El directorio destino ".$destino." no pudo crearse !!.";
}
}else{
$this->error="El directorio destino ".$destino." ya existe !!.";
}
}
function GuardarDestino($destino){
$this->rutadestino=(trim($destino)!="")?$destino:"./";
$this->rutadestino=str_replace("", "/",$this->rutadestino);
if (substr($this->rutadestino,-1)!="/") $this->rutadestino.="/";
if (!file_exists($this->rutadestino)){
if ($this->crearutadestino){
if (!mkdir($this->rutadestino, 0777)){
$this->error="Erro al crear el directorio destino ".$this->rutadestino." !!.";;
$this->rutadestino="./";
}
}else{
$this->error="El directorio destino ".$this->rutadestino." NO existe !!.";
$this->rutadestino="./";
}
}
}
function GuardarNomcampo($nomcampo){
$this->nomcampo=trim($nomcampo);
}
/**/
function fixFileName($fname) {
$fname = strtolower($fname); //minusculas, para no tener problemas con *nix.
$fname = preg_replace('/[^a-z0-9-_.]/im', '_', $fname); //dejamos solo a-z/0-9/-_. reemplazo lo demas por -
return $fname;
}
/**/
function VerNomarchivo(){
return $this->fixFileName($_FILES[$this->nomcampo]["name"]);
}
function VerNomarchivoDest(){
return $this->fixFileName($_FILES[$this->nomcampo]["name"]);
}
function VerError(){
return $this->error;
}
function CrearDestinoSiNoExiste($opcion){
$this->crearutadestino=$opcion;
}
function VerCrearDestinoSiNoExiste(){
return $this->crearutadestino;
}
function ValidarArchivo(){
$this->error="";
if (trim($this->nomcampo)==""){
$this->error="NO se ingreso el nombre del campo tipo file !!";
return;
}
if (!isset($_FILES[$this->nomcampo])){
$this->error="NO se existe el campo tipo file con nombre ".$this->nomcampo."!!";
return;
}
if (trim($_FILES[$this->nomcampo]["name"])==""){
$this->error="NO se ingreso un archivo !!";
return;
}
if ((isset($_POST["max_file_size"])) && ($_POST["max_file_size"]>0)){
if ($_FILES[$this->nomcampo]["size"]<1){
$this->error="El tamaño del archivo '".$_FILES[$this->nomcampo]["name"].
"' NO se pudo comprobar o el tamaño es mayor a ".$this->ConvertirMedida($_POST["max_file_size"]).
". El archivo NO se envia !!";
return;
}else{
if ($_FILES[$this->nomcampo]["size"]>$_POST["max_file_size"]){
$this->error="El archivo '".$_FILES[$this->nomcampo]["name"].
"' tiene un tamaño mayor al permitido (".$this->ConvertirMedida($_POST["max_file_size"]).
"). El archivo NO se envia !!";
return;
}
}
}
if (trim($this->extension)!="*"){
$extarch=strtolower(substr($_FILES[$this->nomcampo]["name"],strrpos($_FILES[$this->nomcampo]["name"],".")));
$extensiones=explode(",", $this->extension);
//if ($extarch!=strtolower($this->extension))
if (!in_array($extarch, $extensiones)){
$this->error="El archivo '".$_FILES[$this->nomcampo]["name"].
"' NO tiene la extension valida '".$this->extension."' !!";
return;
}
}
if (file_exists($this->rutadestino.$_FILES[$this->nomcampo]['name'])) $this->error="Un archivo con nombre y extension '".
$_FILES[$this->nomcampo]['name']."' ya existe en el servidor. El archivo NO se envia !!";
}
}//fin clase
?>
Y por ultimo la clase imglib.class.php que es una clase prediseñada creo que no tiene muchos arreglos por mi parte. Esta se encarga de el diseño de la imagen, sirve para re dimensionar si uno quiere la imagen.
<?php
/*
Library Coded By KnF ([email protected])
Feel free to modify, redistribute or even use :)
=======================================
Properties
=======================================
$width = width of the output image
$height = height of the output image
$maxWidth = this parameter is used to control Aspect ratio in the rezise of an image.
Ex: if you want to leave a margin between the old image and the background color
set this less than the width
$crop = crops the original image if the AS is different from the thumb
$fill = if crop is false this will fill the background with a solid color with $fillCol
$fillCol = Default = '#FFFFFF';
Note: if you dont want to crop the original image or doesn't want fill the background -> Ex: rezise to fixed
width or height keeping the AS, just don specify the width or height
=======================================
Methods
=======================================
=======================================
Error Types
=======================================
error_resource_create
error_fill
error_rezise
error_print_text
error_allocate_color
error_copy_res
error_missing_file
error_opening
error_opening_water
error_opening_logo
error_save
*/
class imglib {
/*Variables Por defecto*/
var $width = 0; //ancho de salida por defecto
var $height = 0; //alto de salida por defecto
var $maxWidth = 0; //ancho maximo de la imagen en la imagen destino
var $crop = false; //recorta la imagen si excede? {true|false} -> def: false;
var $fill = true; //rellena el fondo con un color sólio? {true|false} -> def: true;
var $fillCol = '#FFFFFF';
var $filePath = '';
var $picData;
var $ow = 0;
var $oh = 0;
/*Constructor, open the image and store*/
function imglib($path) { //constructor
ini_set('max_execution_time', '120');
ini_set('memory_limit', '256M');
$this->filePath = $path; //guardo la ruta del archivo original, nose todavia para que, pero por las dudas
if (preg_match('/([Gg][Ii][Ff]|[Jj][Pp][Ee]?[Gg]|[Pp][Nn][Gg]|[Bb][Mm][Pp])$/m', $path, $ext)) {
$extension = strtoupper($ext[1]);//averiguo la ext
}
if (!file_exists($path)) return $this->error('error_missing_file');
switch($extension) { //abro la imagen original y la almaceno en $picData
case 'GIF': $this->picData = @imagecreatefromgif($path); break;
case 'PNG': $this->picData = @imagecreatefrompng($path); break;
case 'BMP': $this->picData = $this->ImageCreateFromBmp($path); break;//linea anueva
default : $this->picData = @imagecreatefromjpeg($path); break; //por defecto jpeg
}
if ($this->picData === false) return $this->error('error_opening');
list($this->ow, $this->oh) = getimagesize($path); //obtengo el tamaño original de la imagen
$this->o_as = $this->ow / $this->oh;
}
function reSize() {
/*si no se definio alto o ancho calculo en base al otro*/
if ($this->height == 0) {
$this->height = ceil($this->width / $this->o_as);
} else if ($this->width == 0) {
$this->width = ceil($this->height * $this->o_as);
}
/*calculo el original_aspectRatio y el AspectRatio*/
$as = $this->width / $this->height;
/*creo la imagen nueva*/
$im = @imagecreatetruecolor($this->width, $this->height);
if ($im === false) return $this->error('error_resource_create');
/*si se tiene que rellenar el fondo lo hago*/
if ($this->fill) {
$bgcolor = $this->parseColor($this->fillCol);
$bgc = @imagecolorallocate($im, $bgcolor['r'], $bgcolor['g'], $bgcolor['b']);
if ($bgc === false) return $this->error('error_allocate_color');
if (!@imagefill($im, 0, 0, $bgc)) return $this->error('error_fill');
}
/* calculamos los nuevos tamaños, relaciones, lalalas y demases */
if (($this->ow > $this->width) || ($this->oh > $this->height)) { //See if we actually need to do anything
if ($this->o_as <= $as) { //If the aspect ratio of the uploaded image is less than or equal to the target size...
if (!$this->crop) {
$newWidth = $this->height * $this->o_as; //Resize the image based on the height
$newHeight = $this->height;
} else {
$newWidth = $this->width; //Resize based on width
$newHeight = $this->width / $this->o_as;
}
} else { //If the ratio is greater...
if (!$this->crop) {
$newWidth = $this->width; //Resize based on width
$newHeight = $this->width / $this->o_as;
} else {
$newWidth = $this->height * $this->o_as; //Resize the image based on the height
$newHeight = $this->height;
}
}
} else {
$newWidth = $this->ow;
$newHeight = $this->oh;
}
if (($newWidth > $this->maxWidth) && ($this->maxWidth != 0)) {
$newWidth = $this->maxWidth;
$newHeight = $this->maxWidth / $this->o_as;
}
/*ahora calculo el centro de la imagen*/
$centro_x = ceil($this->width / 2);
$centro_y = ceil($this->height / 2);
$pos_y = $centro_y - ($newHeight / 2);
$pos_x = $centro_x - ($newWidth / 2);
if (($newWidth < $newHeight) && ($this->crop)) $pos_y = 0;
//le calzo la imagen reziseada al fondo
$rz = @imagecopyresampled($im, $this->picData, $pos_x, $pos_y, 0, 0, $newWidth, $newHeight, $this->ow, $this->oh);
if (!$rz) return $this->error('error_rezise');
//y para terminar guardo la imagen nueva en la imagen principal
@imagedestroy($this->picData);
$this->picData = imagecreatetruecolor($this->width, $this->height);
if ($this->picData === false) return $this->error('error_resource_create');
@imagecopy($this->picData, $im, 0, 0, 0, 0, $this->width, $this->height);
if ($this->picData === false) return $this->error('error_copy_res');
//y destruyo el temporal
@imagedestroy($im);
}
function printText($text, $pos_x, $pos_y, $fontColor = '#FFFFFF', $fontSize = 3) {
$fcolor = $this->parseColor($fontColor);
$fcolor = @imagecolorallocate($this->picData, $fcolor['r'], $fcolor['g'], $fcolor['b']);
if ($fcolor === false) return $this->error('error_allocate_color');
if (!imagestring($this->picData, $fontSize, $pos_x, $pos_y, $text, $fcolor)) return $this->error('error_print_text');
}
function printLogo($logoFile, $pos_x, $pos_y) {
if (preg_match('/([Gg][Ii][Ff]|[Jj][Pp][Ee]?[Gg]|[Pp][Nn][Gg])$/m', $logoFile, $ext)) {
$extension = strtoupper($ext[1]);//averiguo la ext
}
switch($extension) { //abro la imagen original y la almaceno en $picData
case 'GIF': $lupa = @imagecreatefromgif($logoFile); break;
case 'PNG': $lupa = @imagecreatefrompng($logoFile); break;
default : $lupa = @imagecreatefromjpeg($logoFile); break; //por defecto jpeg
}
if ($lupa === false) return $this->error('error_opening_logo');
list($lw, $lh) = @getimagesize($logoFile);
if (!@imagecopy($this->picData, $lupa, $pos_x, $pos_y, 0, 0, $lw, $lh)) return $this->error('error_copy_res');;
}
function waterMark($pngFile, $pos_x, $pos_y, $transp = 30) {
$wi = @imagecreatefrompng($pngFile);
if ($wi === false) return $this->error('error_opening_water');
list($ww, $wh) = @getimagesize($pngFile); //obtengo el tamaño original de la imagen
if (!@imagecopyresampled($this->picData, $wi, $pos_x, $pos_y, 0, 0, $ww, $wh, $ww, $wh)) return $this->error('error_copy_res');
//$ww, $wh, ,
@imagedestroy($wi);
}
function save($ext, $outFile = 'thumb.jpg', $quality = 75){
switch($ext){
case 'JPEG': $res = @imagejpeg($this->picData, $outFile, $quality); break;
case 'PNG': $res = @imagepng($this->picData, $outFile); break;
case 'GIF': $res = @imagegif($this->picData, $outFile); break;
}
if (!$res) return $this->error('error_save');
//imagedestroy($this->picData); //release the image
}
/*utiles*/
function parseColor($strColor) {
if (preg_match('/#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/', $strColor, $cols)) {
$rgb = array(
'r' => base_convert($cols[1], 16, 10),
'g' => base_convert($cols[2], 16, 10),
'b' => base_convert($cols[3], 16, 10)
);
return $rgb;
} else return false;
}
function error($errorType) {
echo 'Se produjo un error al realizar una operacion, el codigo de error es: '.$errorType.'<br />';
return false;
}
//////////////////////////
/////////////////////////
/**
*
* @convert BMP to GD
*
* @param string $src
*
* @param string|bool $dest
*
* @return bool
*
*/
function bmp2gd($src, $dest = false)
{
/*** try to open the file for reading ***/
if(!($src_f = fopen($src, "rb")))
{
return false;
}
/*** try to open the destination file for writing ***/
if(!($dest_f = fopen($dest, "wb")))
{
return false;
}
/*** grab the header ***/
$header = unpack("vtype/Vsize/v2reserved/Voffset", fread( $src_f, 14));
/*** grab the rest of the image ***/
$info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant",
fread($src_f, 40));
/*** extract the header and info into varibles ***/
extract($info);
extract($header);
/*** check for BMP signature ***/
if($type != 0x4D42)
{
return false;
}
/*** set the pallete ***/
$palette_size = $offset - 54;
$ncolor = $palette_size / 4;
$gd_header = "";
/*** true-color vs. palette ***/
$gd_header .= ($palette_size == 0) ? "xFFxFE" : "xFFxFF";
$gd_header .= pack("n2", $width, $height);
$gd_header .= ($palette_size == 0) ? "x01" : "x00";
if($palette_size) {
$gd_header .= pack("n", $ncolor);
}
/*** we do not allow transparency ***/
$gd_header .= "xFFxFFxFFxFF";
/*** write the destination headers ***/
fwrite($dest_f, $gd_header);
/*** if we have a valid palette ***/
if($palette_size)
{
/*** read the palette ***/
$palette = fread($src_f, $palette_size);
/*** begin the gd palette ***/
$gd_palette = "";
$j = 0;
/*** loop of the palette ***/
while($j < $palette_size)
{
$b = $palette{$j++};
$g = $palette{$j++};
$r = $palette{$j++};
$a = $palette{$j++};
/*** assemble the gd palette ***/
$gd_palette .= "$r$g$b$a";
}
/*** finish the palette ***/
$gd_palette .= str_repeat("x00x00x00x00", 256 - $ncolor);
/*** write the gd palette ***/
fwrite($dest_f, $gd_palette);
}
/*** scan line size and alignment ***/
$scan_line_size = (($bits * $width) + 7) >> 3;
$scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size & 0x03) : 0;
/*** this is where the work is done ***/
for($i = 0, $l = $height - 1; $i < $height; $i++, $l--)
{
/*** create scan lines starting from bottom ***/
fseek($src_f, $offset + (($scan_line_size + $scan_line_align) * $l));
$scan_line = fread($src_f, $scan_line_size);
if($bits == 24)
{
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size)
{
$b = $scan_line{$j++};
$g = $scan_line{$j++};
$r = $scan_line{$j++};
$gd_scan_line .= "x00$r$g$b";
}
}
elseif($bits == 8)
{
$gd_scan_line = $scan_line;
}
elseif($bits == 4)
{
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size)
{
$byte = ord($scan_line{$j++});
$p1 = chr($byte >> 4);
$p2 = chr($byte & 0x0F);
$gd_scan_line .= "$p1$p2";
}
$gd_scan_line = substr($gd_scan_line, 0, $width);
}
elseif($bits == 1)
{
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size)
{
$byte = ord($scan_line{$j++});
$p1 = chr((int) (($byte & 0x80) != 0));
$p2 = chr((int) (($byte & 0x40) != 0));
$p3 = chr((int) (($byte & 0x20) != 0));
$p4 = chr((int) (($byte & 0x10) != 0));
$p5 = chr((int) (($byte & 0x08) != 0));
$p6 = chr((int) (($byte & 0x04) != 0));
$p7 = chr((int) (($byte & 0x02) != 0));
$p8 = chr((int) (($byte & 0x01) != 0));
$gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
}
/*** put the gd scan lines together ***/
$gd_scan_line = substr($gd_scan_line, 0, $width);
}
/*** write the gd scan lines ***/
fwrite($dest_f, $gd_scan_line);
}
/*** close the source file ***/
fclose($src_f);
/*** close the destination file ***/
fclose($dest_f);
return true;
}
/**
*
* @ceate a BMP image
*
* @param string $filename
*
* @return bin string on success
*
* @return bool false on failure
*
*/
function ImageCreateFromBmp($filename)
{
/*** create a temp file ***/
$tmp_name = tempnam("/tmp", "GD");
/*** convert to gd ***/
if($this->bmp2gd($filename, $tmp_name))
{
/*** create new image ***/
$img = imagecreatefromgd($tmp_name);
/*** remove temp file ***/
unlink($tmp_name);
/*** return the image ***/
return $img;
}
return false;
}
}
?>
Como pueden ver, las imagenes se guarda en 3 dimensiones, la primera es tal cual la original, y las otras dos son las dimesiones que lee de una tabla Mysql llamada tamano, donde en mi caso le puse dos medidas, una media y otra pequeña.
El diseño de las BD es el siguiente :
CREATE TABLE `fotos` (
`id_foto` int(11) NOT NULL auto_increment,
`nombre` varchar(150) NOT NULL,
`titulo` varchar(150) NOT NULL,
`descripcion` text NOT NULL,
`fecha` date NOT NULL,
`id_galeria` varchar(100) NOT NULL,
`enlace` varchar(250) NOT NULL,
PRIMARY KEY (`id_foto`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1
CREATE TABLE `galeria` (
`id_galeria` int(11) NOT NULL auto_increment,
`nombre` varchar(100) NOT NULL,
`visible` tinyint(1) NOT NULL,
`destacado` tinyint(1) NOT NULL,
`fecha` date NOT NULL,
`nombre_real` varchar(250) NOT NULL,
`foto` varchar(250) NOT NULL,
PRIMARY KEY (`id_galeria`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1
CREATE TABLE `tamano` (
`tipo` varchar(20) NOT NULL,
`ancho` int(5) NOT NULL,
`largo` int(5) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
También les dejo todos los archivos para que lo puedan descargar, los único que les quedaría es crear las tablas que para mayor comodidad esta el archivo .sql.
Saludos y espero que les sea útil.