Foros del Web » Programando para Internet » Javascript »

redimensionar imagen Js o php?

Estas en el tema de redimensionar imagen Js o php? en el foro de Javascript en Foros del Web. Hola foreros no se si esto apareció en los faqs pero no encontré nada que me ayude Resulta que tengo una serie de imágenes en ...
  #1 (permalink)  
Antiguo 26/06/2008, 12:00
 
Fecha de Ingreso: febrero-2004
Mensajes: 134
Antigüedad: 20 años, 3 meses
Puntos: 0
redimensionar imagen Js o php?

Hola foreros no se si esto apareció en los faqs pero no encontré nada que me ayude
Resulta que tengo una serie de imágenes en una base de datos donde pedí que sean subidas de cierto tamaño y no lo hicieron... entonces al haber una imagen mas ancha de lo debido se me deforma el site...ok.
Entonces buscando en la red vi que con js se puede hacer esto...

<img src="cover/129604.jpg" onload="if(this.width > 100) {this.width=100}" />

Huu dije la solución a mis problemas... pero no fue así, resulta que para ver la imagen desde la base de datos tengo armado esto...

Código PHP:
<?php 
         $imagen 
$reg['tapa'];
         if(
$imagen=="cover/"){         
         echo 
"<img src=\"cover/imagen_no_dis.jpg\">"
         }else{
         echo  
"<img src='".$reg['tapa']."'>"; }
 
?>
entonces me dije esto debe ser asi...

Código PHP:
<?php 
         $imagen 
$reg['tapa'];
         if(
$imagen=="cover/"){         
         echo 
"<img src=\"cover/imagen_no_dis.jpg\">"
         }else{
         echo  
"<img src='".$reg['tapa'].onload="if(this.width > 100) {this.width=100}\"'>"; }
 
?>
Salir y entrar de php con "\" pero nada...existe la forma de poder meter ese js en el medio del php?
o existe algo parecido en php que seguramente desconozco?
Estuve leyendo sobre librerías gd y me parece que no tengo en mi servidor porque los scripts que probé no anduvo ninguno.
Desde ya les agradezco el tiempo que le han dedicado a este problema
  #2 (permalink)  
Antiguo 26/06/2008, 12:06
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: redimensionar imagen Js o php?

lo que sucede es que estas prestando poca atencion a la sintaxis.... ese es tu error

Código PHP:
<?php 
         $imagen 
$reg['tapa'];
         if(
$imagen=="cover/"){         
         echo 
"<img src=\"cover/imagen_no_dis.jpg\">"
         }else{
         echo  
"<img src='".$reg['tapa']"' onload='if(this.width > 100) {this.width=100}'>"; }
 
?>
deveras.... pon mas atención, suerte!
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 26/06/2008, 12:14
Avatar de overflown  
Fecha de Ingreso: marzo-2008
Ubicación: En algún rinconcito de inet
Mensajes: 6
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: redimensionar imagen Js o php?

Podés usar php ingeniandotelas un poco en el como usar el width o height específico o máximo reduciendolo o usando alguna relación de aspecto con variables.. con simples if preguntando si supera el maximo tamaño que vos asignaste.. acá te dejo un ejemplo en js que tengo en un foro mío y funciona.. no lo entiendo mucho pero puede que te sirva, saludos y éxitos :)

Código:
NcodeImageResizer.IMAGE_ID_BASE = 'ncode_imageresizer_container_';
NcodeImageResizer.WARNING_ID_BASE = 'ncode_imageresizer_warning_';

function NcodeImageResizer(id, img) {
	this.id = id;
	this.img = img;
	this.originalWidth = 0;
	this.originalHeight = 0;
	this.warning = null;
	this.warningTextNode = null;
	
	img.id = NcodeImageResizer.IMAGE_ID_BASE+id;
}

NcodeImageResizer.getNextId = function() {
	id = 1;
	while(document.getElementById(NcodeImageResizer.IMAGE_ID_BASE+id) != null) {
		id++;
	}
	return id;
}

NcodeImageResizer.createOnId = function(id) {
	return NcodeImageResizer.createOn(document.getElementById(id));
}

NcodeImageResizer.createOn = function(img) {
	if(!img.tries || typeof img.tries == 'undefined') {
		img.tries = 1;
	} else {
		img.tries++;
	}
	
	if((img.width == 0 || img.height == 0) && img.tries < 4) {
		var ran = Math.floor(Math.random()*100000);
		img.id = ran;
		setTimeout('NcodeImageResizer.createOnId("'+ran+'");', 500);
		return;
	}
	
	isRecovery = false; // if this is a recovery from QuickEdit, which only restores the HTML, not the OO structure
	if(img.id && img.id.indexOf(NcodeImageResizer.IMAGE_ID_BASE) == 0 && document.getElementById(NcodeImageResizer.WARNING_ID_BASE+img.id.substr(NcodeImageResizer.IMAGE_ID_BASE.length)) != null) {
		newid = img.id.substr(NcodeImageResizer.IMAGE_ID_BASE.length);
		resizer = new NcodeImageResizer(newid, img);
		isRecovery = true;
		resizer.restoreImage();
	} else {
		newid = NcodeImageResizer.getNextId();
		resizer = new NcodeImageResizer(id, img);
	}
	
	if (resizer.originalWidth == 0) resizer.originalWidth = img.width;
	if (resizer.originalHeight == 0) resizer.originalHeight = img.height;
	
	if((NcodeImageResizer.MAXWIDTH > 0 && resizer.originalWidth > NcodeImageResizer.MAXWIDTH) || (NcodeImageResizer.MAXHEIGHT > 0 && resizer.originalHeight > NcodeImageResizer.MAXHEIGHT)) {
		if(isRecovery) {
			resizer.reclaimWarning(warning);
		} else {
			resizer.createWarning();
		}
		resizer.scale();
	}
}

NcodeImageResizer.prototype.restoreImage = function() {
	newimg = document.createElement('IMG');
	newimg.src = this.img.src;
	this.img.width = newimg.width;
	this.img.height = newimg.height;
}

NcodeImageResizer.prototype.reclaimWarning = function() {
	warning = document.getElementById(NcodeImageResizer.WARNING_ID_BASE+newid);
	
	this.warning = warning;
	this.warningTextNode = warning.firstChild.firstChild.childNodes[1].firstChild;
	this.warning.resize = this;
	
	this.scale();
}

NcodeImageResizer.prototype.createWarning = function() {
	mtable = document.createElement('TABLE');
	mtbody = document.createElement('TBODY');
	mtr = document.createElement('TR');
	mtd1 = document.createElement('TD');
	mtd2 = document.createElement('TD');
	mimg = document.createElement('IMG');
	mtext = document.createTextNode('');
	
	mimg.src = 'images/statusicon/wol_error.gif';
	mimg.width = 16;
	mimg.height = 16;
	mimg.alt = '';
	mimg.border = 0;
	
	mtd1.width = 20;
	mtd1.className = 'td1';
	
	mtd2.unselectable = 'on';
	mtd2.className = 'td2';
	
	mtable.className = 'ncode_imageresizer_warning';
	mtable.textNode = mtext;
	mtable.resize = this;
	mtable.id = NcodeImageResizer.WARNING_ID_BASE+this.id;
	
	mtd1.appendChild(mimg);
	mtd2.appendChild(mtext);
	
	mtr.appendChild(mtd1);
	mtr.appendChild(mtd2);
	
	mtbody.appendChild(mtr);
	
	mtable.appendChild(mtbody);
	
	this.img.parentNode.insertBefore(mtable, this.img);
	
	this.warning = mtable;
	this.warningTextNode = mtext;
}

NcodeImageResizer.prototype.scale = function() {
	this.img.height = this.originalHeight;
	this.img.width = this.originalWidth;
	
	if(NcodeImageResizer.MAXWIDTH > 0 && this.img.width > NcodeImageResizer.MAXWIDTH) {
		resized = true;
		this.img.height = (NcodeImageResizer.MAXWIDTH / this.img.width) * this.img.height;
		this.img.width = NcodeImageResizer.MAXWIDTH;
	}
	
	if(NcodeImageResizer.MAXHEIGHT > 0 && this.img.height > NcodeImageResizer.MAXHEIGHT) {
		resized = true;
		this.img.width = (NcodeImageResizer.MAXHEIGHT / this.img.height) * this.img.width;
		this.img.height = NcodeImageResizer.MAXHEIGHT;
	}
	
	this.warning.width = this.img.width;
	this.warning.onclick = function() { return this.resize.unScale(); }
	
	if(this.img.width < 450) {
		this.warningTextNode.data = vbphrase['ncode_imageresizer_warning_small'];
	} else if(this.img.fileSize && this.img.fileSize > 0) {
		this.warningTextNode.data = vbphrase['ncode_imageresizer_warning_filesize'].replace('%1$s', this.originalWidth).replace('%2$s', this.originalHeight).replace('%3$s', Math.round(this.img.fileSize/1024));
		//mtext.data = '<phrase 1="'+this.originalWidth+'" 2="'+this.originalHeight+'" 3="'+Math.round(this.img.fileSize/1024)+'">$vbphrase[ncode_imageresizer_warning_filesize]</phrase>';
	} else {
		this.warningTextNode.data = vbphrase['ncode_imageresizer_warning_no_filesize'].replace('%1$s', this.originalWidth).replace('%2$s', this.originalHeight);
		//mtext.data = '<phrase 1="'+this.originalWidth+'" 2="'+this.originalHeight+'">$vbphrase[ncode_imageresizer_warning_no_filesize]</phrase>';
	}
	
	return false;
}

NcodeImageResizer.prototype.unScale = function() {
	switch(NcodeImageResizer.MODE) {
		case 'samewindow':
			window.open(this.img.src, '_self');
			break;
		case 'newwindow':
			window.open(this.img.src, '_blank');
			break;
		case 'enlarge':
		default:
			this.img.width = this.originalWidth;
			this.img.height = this.originalHeight;
			this.img.className = 'ncode_imageresizer_original';
			if(this.warning != null) {
				this.warningTextNode.data = vbphrase['ncode_imageresizer_warning_fullsize'];
				this.warning.width = this.img.width;
				this.warning.onclick = function() { return this.resize.scale() };
			}
			break;
	}
	
	return false;

}
  #4 (permalink)  
Antiguo 26/06/2008, 12:17
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: redimensionar imagen Js o php?

eso es ingeniárselas??? sin estar entendiendo el código... que fácil!

:D

PDTA: para el código... usa [code], [html], [php], etc, etc... así no ocupa todo el largo de la pantalla...
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 26/06/2008, 12:18
Avatar de overflown  
Fecha de Ingreso: marzo-2008
Ubicación: En algún rinconcito de inet
Mensajes: 6
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: redimensionar imagen Js o php?

No, hablo de ingeniarselas en php!! no en ese código que no llego a entender.. que a mi gusto es más simple, también porque basta con definir el alto y ancho de la imagen para lograr el resize (supongo que en js también) pero si tenés por ejemplo un php con las fuciones podés incluirle una que se llame "resize" o "redimensionamiento" y ahi meterle eso de que si la imagen supera cierta dimension, que la pase a ésta otra (usando el width y el height) y ajustandolo a sus necesidades y la otra medida digamos que mantenga el aspecto, por ejemplo en una 800x600 no quiero que pase el ancho de 800 quiero que el máximo sea 500, entonces hago que el width pase a valer 500 y despues hacer una regla de 3 simple para mantener el aspecto creo que ni se lo tengo que explicar como se hace, Saludos.

PD: Con respecto a esas que ya tenés en la database deberías usar un while y revisar de punta a punta las imagenes para proceder con el resize, podes crear un php solamente para hacer eso y despues lo borras, dejás simplemente las funciones de resize para futuras subidas.

Última edición por overflown; 26/06/2008 a las 12:25
  #6 (permalink)  
Antiguo 27/06/2008, 14:01
 
Fecha de Ingreso: febrero-2004
Mensajes: 134
Antigüedad: 20 años, 3 meses
Puntos: 0
Respuesta: redimensionar imagen Js o php?

Perdón por la demora pero recién me pude conectar!!!
Pateketrueke gracias por la respuesta anda de perlas, Overflow fuiste claro con lo de ingeniárselas no hace falta que sobreexpliques nada.
Gracias a los dos por el tiempo. OverFlow estoy estudiando tu script para ponerlo en uso.
  #7 (permalink)  
Antiguo 27/06/2008, 14:25
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: redimensionar imagen Js o php?

Tema trasladado a Javascript.
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 10:01.