28
Abr

En este artículo mostraré una implementación del plugin sfThumbnailPlugin para redimensionar imágenes. Idealmente usado para la creación de las previsualizaciones de fotografías en nuestros sitios web.

Lo necesario:

  1. Instalar el plugin sfThumbnailPlugin
    symfony plugin:install sfThumbnailPlugin
  2. Tener configurada la BD, y el modelo implementado previamente con al menos un campo para guardar imágenes varchar(50).
  3. Tener un módulo creado con el “Admin generator” de Symfony

Procedimiento

Primero, configuraremos el formulario en la clase correspondiente. Tomaré por ejemplo un módulo para subir noticias a un sitio web.

Widget

Usaremos el widget para subir archivo editable sfWidgetFormInputFileEditable, ya que este nos permite mostrar la imagen que se ha subido además de dar la opción de eliminarla cuando existe.

NoticiaForm.class.php

$this->widgetSchema['imagen'] = new sfWidgetFormInputFileEditable(array(
   'label'     => 'Imagen Principal',
   'file_src'  => '/uploads/noticias/thumbs/'.$this->getObject()->getImagen(),
   'is_image'  => true,
   'edit_mode' => !$this->isNew(),
   'template'  => '<div>%file%<br /><label></label>%input%<br /><label></label>%delete% Eliminar imagen actual</div>',
));

Explicación de lo anterior:

  • Label nos permite modificar la etiqueta del campo en el formulario.
  • File_src provee la ruta a la imagen ya subida, para mostrarla.
  • Is_image, si no me equivoco le permite a Symfony conocer que estamos trabajando con una imagen (si alguien sabe su utilidad, comente).
  • Edit_mode hace que la imagen sólo se muestre una vez que hayamos creado el registro, por ende cuando se ha subido ya algo.
  • Template, es el formato con el que queremos mostrar la previsualización de la imagen.

Validator

El validador es el que finalmente sube y guarda la imagen, por lo tanto es donde debemos usar el plugin sfThumbnailPlugin.

NoticiaForm.class.php

$this->validatorSchema['imagen'] = new sfValidatorFile(array(
   'required'   => false,
   'mime_types' => 'web_images',
   'path' => sfConfig::get('sf_upload_dir').'/noticias/original',
   'validated_file_class' => 'sfResizedFile',
));

Explicación.

  • Required, ya sabemos.
  • Mime_types permite decir qué archivos se pueden subir, los que son permitidos, en este caso sólo imágenes.
  • Path es usado para indicar la ruta donde queremos que se guarden las imágenes (de tamaño original, o ampliado).
  • Validated_file_class es el parámetro importante aquí, nos permite decir que usaremos una clase propia para manejar la imagen subida.

sfResizedFile es una clase nueva, la cual obtuve desde el Foro de Symfony. Créditos para malas.

/lib/sfResizedFile.class.php

/**
 * sfResizedFile represents a resized uploaded file.
 *
 * @package    symfony
 * @subpackage validator
 * @author     Malas
 * @version    0.1
 */
class sfResizedFile extends sfValidatedFile
{

	/**
	 * Saves the uploaded file.
	 *
	 * This method can throw exceptions if there is a problem when saving the file.
	 *
	 * If you don't pass a file name, it will be generated by the generateFilename method.
	 * This will only work if you have passed a path when initializing this instance.
	 *
	 * @param  string $file      The file path to save the file
	 * @param  int    $fileMode  The octal mode to use for the new file
	 * @param  bool   $create    Indicates that we should make the directory before moving the file
	 * @param  int    $dirMode   The octal mode to use when creating the directory
	 *
	 * @return string The filename without the $this->path prefix
	 *
	 * @throws Exception
	 */
	public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777)
	{
		if (is_null($file))
		{
			$file = $this->generateFilename();
		}

		if ($file[0] != '/' && $file[0] != '\\' && !(strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/')))
		{
			if (is_null($this->path))
			{
				throw new RuntimeException('You must give a "path" when you give a relative file name.');
			}

			$smallFile = $this->path.DIRECTORY_SEPARATOR.'s_'.$file;
			$file = $this->path.DIRECTORY_SEPARATOR.$file;
		}

		// get our directory path from the destination filename
		$directory = dirname($file);
		if (!is_readable($directory))
		{
			if ($create && !mkdir($directory, $dirMode, true))
			{
				// failed to create the directory
				throw new Exception(sprintf('Failed to create file upload directory "%s".', $directory));
			}

			// chmod the directory since it doesn't seem to work on recursive paths
			chmod($directory, $dirMode);
		}
		if (!is_dir($directory))
		{
			// the directory path exists but it's not a directory
			throw new Exception(sprintf('File upload path "%s" exists, but is not a directory.', $directory));
		}
		if (!is_writable($directory))
		{
			// the directory isn't writable
			throw new Exception(sprintf('File upload path "%s" is not writable.', $directory));
		}

		// copy the temp file to the destination file
		$thumbnail = new sfThumbnail(100, 100, true, true, 85, 'sfGDAdapterCuttingOff');
		$thumbnail->loadFile($this->getTempName());
		$thumbnail->save($smallFile, 'image/jpeg');

		$thumbnail = new sfThumbnail(400, 400, true, true, 85, 'sfGDAdapter');
		$thumbnail->loadFile($this->getTempName());
		$thumbnail->save($file, 'image/jpeg');

		// chmod our file
		chmod($smallFile, $fileMode);
		chmod($file, $fileMode);

		$this->savedName = $file;
		return is_null($this->path) ? $file : str_replace($this->path.DIRECTORY_SEPARATOR, '', $file);
	}

}

Para crear nuestros thumbnails, solo sebemos agregar cada uno como se muestra en negrita:

$thumbnail = new sfThumbnail ($maxWidth = null, $maxHeight = null, $scale = true, $inflate = true, $quality = 75, $adapterClass = null, $adapterOptions = array())

Si necesitamos 5 tamaños diferente, debemos agregar 5 veces la creación y guardado de un objeto sfThumbnail.

Finalmente, limpiar la cache del proyecto y probar cómo funciona el redimensionado de imágenes.

NOTA: Si aparece el error de que no existe sfGDAdapterCuttingOff, simplemente eliminar esa declaración. Se debe a que no está completamente instalado GD. En mi caso funcionó sin necesidad de usar ese parámetro.

Visto en Foro de Symfony

, , , ,

110 Responses to “sfThumbnailPlugin y Admin Generator: redimensionar imágenes”

  • Thanks for every other magnificent article. The place else may
    just anybody get that type of info in such a perfect manner
    of writing? I have a presentation next week, and I am at the look for such information.

  • Esa es una muy buena gran particular fresca a la
    blogosfera. Simple precisa info … Gracias por usted compartiendo este.
    Una lectura obligada artículo !

  • We’re a group of volunteers and starting a brand new scheme in our community.
    Your website provided us with valuable information and work on .
    You have a formidable activity and our whole neighborhood will likely be thankful to you .

    Undeniably imagine that you said . Your favorite reason seemed to be on the web simple factor to keep in mind of .
    I tell you , i certainly get annoyed same as any other people people think concerns not realize about .

    You controlled and also defined everything managed to
    hit the nail on the top without having side effect
    , people could take a signal. Will likely be back to get more.
    Thanks

  • We’re a flock a group of volunteers and starting a brand new scheme in our community.
    Your website provided us with helpful helpful and paintings on .
    You have a formidable task and our all the group could be grateful to
    you .
    Unquestionably believe which you stated . Your favorite justification seemed to be
    at the internet simple factor to understand of .

    I tell you , i certainly get annoyed at the same time while consider think concerns not recognize about .
    You controlled perfectly as out everything managed to hit the nail on the top no need side effect
    , other folks could take a signal. Will probably be back to get more.
    Thank you

  • I’m impressed, I have to admit. Seldom do
    I encounter a blog that’s both educative and entertaining, and without a doubt, you have hit the
    nail on the head. The problem is an issue that
    too few folks are speaking intelligently about. I am very happy that I stumbled
    across this during my hunt for something relating
    to this.

  • This includes vacuum and contractor compressed air.

    He is to assure that they should b able to do.

    We hope that it get hung contractor in a professional. Really efficient Atlanta home heating and
    air conditioning.

  • Yes! Finally someone writes about thank you
    cards.

  • Way cool! Some extremely valid points! I appreciate you
    penbing tyis write-up and the rest of the site is also really good.

  • But does it tell me what the majority of the graduates in this category.
    Flash web design firm doesn’t have any sister concerns? Even if you decide to delay helping you if
    they are looking for. At Osprosys, search engine optimization we must get involved.
    Call them to return to their businesses.

  • It’s a pity you don’t have a donate button!
    I’d certainly donate to this fantastic blog! I suppose for now i’ll settle for
    book-marking and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this site with my Facebook
    group. Talk soon!

  • Due to the company’s vice chairman and Al LaPierre, former state representative Jay Hoffman will run unopposed in the contract.
    The arrest of 18 home repair business, if there is a
    company out of a tread or landing tread which protrudes beyond the scope really be
    expected the the professional manner. Try to school bus
    hire, should be done. A roofing contractor has a right to direct attention to cut-in areas around
    doors, members are made are satisfactory.

  • What’s up to all, how is everything, I think every one is getting more from this web page, and your views
    are nice in favor of new viewers.

  • I have read so many articles on the topic of the blogger lovers
    however this article is in fact a nice paragraph, keep it up.

  • Roof installation is usually a considerable investment,
    so you always have to be careful with your commercial roofing or residential roofing requirements.
    Many acting classes specialize in helping actors learn to use dialects effectively.
    Be sure to get a copy of this before you let the work commence.

  • Los post mе gustɑron mas toɗo hay que decirlo Animo!

  • No esyοy plenamente de acuerdo con la forma de decirlo, sin embargo cгeo que est bien el contenido.Sаludos

  • Minecraft se puede jugar como el LEGO, pero la construcción es solo uno de sus
    aspectos.

  • Muy chulo, me ha gustado mucho

  • El día de hoy en día consumimos considerablemente más alimentos y bebidas de
    formación ácida que alimentos y bebidas de formación alcalina.

  • Piscinas Waterair es el líder de la piscina enterrada en kit y también inventó el concepto de
    la piscina con armazón de acero ondulado.

  • No hay emoción más intensa para un inventor que ver una de sus creaciones funcionando

  • Thanks for some other magnificent article. Whre else may
    ust anyone get that kind of information in such a perfect way of writing?

    I have a presentation subsequent week, and I’m at the search for such info.

  • 私はあなたが多くの本当に面白いのポイントを作ったと思います。ないだけでなく、多くの皆さんは、実際にはそれについて、あなただけやった方向を思うだろう。私は実際に明らかにされているこのテーマについてはあまりがあると感心し、あなたはとてもかなりクラスで、そのようにうまくそれを作りました。トップノッチ1、男!右ここで非常に特別なもの。

  • Eli

    Tengo muchas hobbies.nombre Penney desde Margarethen Am Moos

  • サイト、私は実際 |ながら|ものの|でもしばらく、誤ってあなたの位置します私は探していた私は今ここだけ驚異的なポストのための歓声を言うのが好きでしたし、すべてのラウンド面白いウェブサイトサイト。 仕事 優れた素晴らしい素晴らしいまで| 維持おくしてください。あなた純粋

  • There are definitely pently of details like that to take into consideration. That may be a nice level to convey up. I provide the thoughts above as common inspiration however clearly there are questions like the one you convey up where crucial thing will likely be working in honest good faith. I don?t know if best practices have emerged round things like that, however I am positive that your job is clearly identified as a fair game. Both boys and girls feel the influence of just a second’s pleasure, for the rest of their lives.

  • No se deben tomar las valoraciones de forma personal ni
    contestar cuando prima el enfurezco.

    • Hej Erik, en frÃ¥ga som jag skulle vilja att du kollade upup..H.r kommer det sig att Ivpa larmen minskat med c:a hälften sedan Medhelp tog över frÃ¥n Sos alarm i november 2011.Har inte Medhelp samma kriterier som Sos alarm?

    • Happy Thanksgiving Shannon!! You are so sweet and I am thankful for you and the kind hearted messages you send me because it does inspire me to push myself harder and keep my mind in the right place to not give up, for thank I am so grateful! Yay! I will post pics the day of from my phone!!

    • That’s a creative answer to a difficult question

  • El año 1950 ingresó en el Seminario Menor de San J., donde realizó
    el Bachillerato; posteriormente cursó los estudios de Filosofía y Teología en el Seminario Mayor San Fulgencio.

  • It’s wonderful to have you on our side, haha!

    • Many many qutliay points there.

    • Plan for the week for food: make a bunch of grilled chicken plus some stir fry veggies, tilapia (not sure how I will cook it), Chicken sausage meal with veggies, smoothies, protein perfect pancakes.Workouts: Power Yoga, boxing, lift upper body and lower body with extra cardio for warm-up cool down and a couple of HIIT workouts on the days I work : ) ( I work 12 hour shifts so the quick but effective HIIT workouts are perfect!) Like sharing ideas, always looking for ways to spice it up!!

    • mutta eikös se mennyt jotenkin niin, että joulun ja uudenvuoden välissä voi syödä niin paljon kuin jaksaa eikä lihoa, jos uudenvuoden ja joulun välillä syö terveellisesti? :)ei muutenkaan kannata stressata joulusyömisistä, kerran vuodessahan on lupa syödä “paremmin”

    • Una piccola, piccolissima, buona notizia: ho letto ieri (se non ricordo male sul sito de “La Stampa”) che Senderos non ha alcuna intenzione di tornare a Londra. Intanto è uscito il calendario della Premier : l’inizio è abbastanza…scioccante ; alla prima giornata, il 15 agosto, ci accoglierà l’Everton, mentre il 29 saremo di scena all’Old Trafford…confesso che un po’ mi tremano le gambe…

    • Ich habe genau ein Plugin (Glims) in meinem Safari installiert. Und dank der grafischen History finde ich auch ziemlich schnell einen versehentlich geschlossenen Tab wieder, sollte mir das mal passieren (was selten der Fall ist). Safari ist rasendschnell, deswegen mag ich ihn. Von den Features her ist er kaum besser als der IE, zugegeben. Hat nix mit Apple-Jünger oder nicht zu tun, Speed zählt für mich mehr als Featuritis.

    • this is a really awesome blog!we really love the style of your blog.we are now following u, visit our new Photography blog:)kind regardswww.vier-augen.blogspot.com

  • Thanks Sharla! How fun is that!?! I ordered one. I need to find some time where I can catch up on friend's blogs. I miss you guys! Hope you are well and have a fantabulous Thanksgiving!

  • , "It has become clear that the heads of state of governmentdon't want strong political figures — especially when it comes to the president of European Council. "Belgian Prime Minister, Herman Van Rompuy, has emerged as a front-runner for the top job.Also in the runningis a Dutch Prime Minister, former Latvian president, and Luxembourg's Prime MinisterFormer British Prime Minister, Tony Blair, could be a surprise appointment. He has neither entered the election race, nor ruled himself out.

  • went through your pastel recipe, but I don’t think you included enough liquid? Perhaps hot water needs to be added to your ingredient list?

  • Caro Padre Danilo, sì siamo sicuri che “Ruah” significa spirito, soffio… quello che si libra sulle acque in Genesi… ed è femminile in ebraicol’anima ha diversi nomi, a seconda dei ‘livelli’: a partire da nephesh (che indica anche la vita personale), neshama, (l’anima spirtuale) e oltre…

  • It combines state-of-the-art, standard medical therapies with other therapies that are cautiously chosen and shown to be effective and secure.

  • What’s up to every body, it’s my first pay a visit of this web site; this blog carries amazing and really fine material designed for visitors.

  • Just ᴡish tto say уour artile is ass astonishing.
    Ƭhe coarity іn yοur post іs јust coll and i can assume yoᥙ’rе ann
    expert on thiѕ subject. Wеll witһ ypur permission аllow me to
    gra ʏoսr feed to ҝeep up tⲟ date with forthfoming post.
    Тhanks a million andd рlease continue thee gratifying ѡork.

to Zella