<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Symfony por David Vega &#187; Plugins</title>
	<atom:link href="http://symfony.davidvega.net/category/plugins/feed/" rel="self" type="application/rss+xml" />
	<link>http://symfony.davidvega.net</link>
	<description>Tips para desarrolladores</description>
	<lastBuildDate>Tue, 08 Jun 2010 17:11:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>sfThumbnailPlugin y Admin Generator: redimensionar imágenes</title>
		<link>http://symfony.davidvega.net/2009/04/sfthumbnailplugin-y-admin-generator-redimensionar-imagenes/</link>
		<comments>http://symfony.davidvega.net/2009/04/sfthumbnailplugin-y-admin-generator-redimensionar-imagenes/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 15:48:39 +0000</pubDate>
		<dc:creator>David Vega</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Symfony 1.2]]></category>
		<category><![CDATA[admin generator]]></category>
		<category><![CDATA[imagenes]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[thumbnail]]></category>
		<category><![CDATA[thumbnails]]></category>

		<guid isPermaLink="false">http://symfony.davidvega.net/?p=22</guid>
		<description><![CDATA[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: Instalar el plugin sfThumbnailPlugin symfony plugin:install sfThumbnailPlugin Tener configurada la BD, y el modelo implementado previamente con al menos un campo para guardar imágenes varchar(50). Tener un [...]]]></description>
			<content:encoded><![CDATA[<p>En este artículo mostraré una implementación del plugin <a href="http://www.symfony-project.org/plugins/sfThumbnailPlugin">sfThumbnailPlugin</a> para redimensionar imágenes. Idealmente usado para la creación de las previsualizaciones de fotografías en nuestros sitios web.</p>
<p><strong>Lo necesario:</strong></p>
<ol>
<li>Instalar el plugin <a href="http://www.symfony-project.org/plugins/sfThumbnailPlugin">sfThumbnailPlugin</a><br />
<code>symfony plugin:install sfThumbnailPlugin</code></li>
<li>Tener configurada la BD, y el modelo implementado previamente con al menos un campo para guardar imágenes varchar(50).</li>
<li>Tener un módulo creado con el &#8220;Admin generator&#8221; de Symfony</li>
</ol>
<p><strong>Procedimiento</strong></p>
<p>Primero, configuraremos el formulario en la clase correspondiente. Tomaré por ejemplo un módulo para subir noticias a un sitio web.</p>
<p>Widget</p>
<p>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.</p>
<p><code>NoticiaForm.class.php</code></p>
<pre>$this-&gt;widgetSchema['imagen'] = new sfWidgetFormInputFileEditable(array(
   'label'     =&gt; 'Imagen Principal',
   'file_src'  =&gt; '/uploads/noticias/thumbs/'.$this-&gt;getObject()-&gt;getImagen(),
   'is_image'  =&gt; true,
   'edit_mode' =&gt; !$this-&gt;isNew(),
   'template'  =&gt; '&lt;div&gt;%file%&lt;br /&gt;&lt;label&gt;&lt;/label&gt;%input%&lt;br /&gt;&lt;label&gt;&lt;/label&gt;%delete% Eliminar imagen actual&lt;/div&gt;',
));</pre>
<p>Explicación de lo anterior:</p>
<ul>
<li>Label nos permite modificar la etiqueta del campo en el formulario.</li>
<li>File_src provee la ruta a la imagen ya subida, para mostrarla.</li>
<li>Is_image, si no me equivoco le permite a Symfony conocer que estamos trabajando con una imagen (si alguien sabe su utilidad, comente).</li>
<li>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.</li>
<li>Template, es el formato con el que queremos mostrar la previsualización de la imagen.</li>
</ul>
<p>Validator</p>
<p>El validador es el que finalmente sube y guarda la imagen, por lo tanto es donde debemos usar el plugin sfThumbnailPlugin.</p>
<p><code>NoticiaForm.class.php</code></p>
<pre>$this-&gt;validatorSchema['imagen'] = new sfValidatorFile(array(
   'required'   =&gt; false,
   'mime_types' =&gt; 'web_images',
   'path' =&gt; sfConfig::get('sf_upload_dir').'/noticias/original',
   'validated_file_class' =&gt; 'sfResizedFile',
));</pre>
<p>Explicación.</p>
<ul>
<li>Required, ya sabemos.</li>
<li>Mime_types permite decir qué archivos se pueden subir, los que son permitidos, en este caso sólo imágenes.</li>
<li>Path es usado para indicar la ruta donde queremos que se guarden las imágenes (de tamaño original, o ampliado).</li>
<li>Validated_file_class es el parámetro importante aquí, nos permite decir que usaremos una clase propia para manejar la imagen subida.</li>
</ul>
<p>sfResizedFile es una clase nueva, la cual obtuve desde el <a href="http://forum.symfony-project.org/index.php/mv/msg/19917/76339/">Foro de Symfony</a>. Créditos para <a href="http://forum.symfony-project.org/index.php/u/4486/">malas</a>.</p>
<p><code>/lib/sfResizedFile.class.php</code></p>
<pre>/**
 * 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-&gt;path prefix
	 *
	 * @throws Exception
	 */
	public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777)
	{
		if (is_null($file))
		{
			$file = $this-&gt;generateFilename();
		}

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

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

		// get our directory path from the destination filename
		$directory = dirname($file);
		if (!is_readable($directory))
		{
			if ($create &amp;&amp; !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
		<strong>$thumbnail = new sfThumbnail(100, 100, true, true, 85, 'sfGDAdapterCuttingOff');
		$thumbnail-&gt;loadFile($this-&gt;getTempName());
		$thumbnail-&gt;save($smallFile, 'image/jpeg');

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

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

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

}</pre>
<p>Para crear nuestros thumbnails, solo sebemos agregar cada uno como se muestra en negrita:</p>
<pre>$thumbnail = new sfThumbnail ($maxWidth = null, $maxHeight = null, $scale = true, $inflate = true, $quality = 75, $adapterClass = null, $adapterOptions = array())</pre>
<p>Si necesitamos 5 tamaños diferente, debemos agregar 5 veces la creación y guardado de un objeto sfThumbnail.</p>
<p>Finalmente, limpiar la cache del proyecto y probar cómo funciona el redimensionado de imágenes.</p>
<p>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.</p>
<p>Visto en  <a href="http://forum.symfony-project.org/index.php/mv/msg/19917/76339/">Foro de Symfony</a></p>
]]></content:encoded>
			<wfw:commentRss>http://symfony.davidvega.net/2009/04/sfthumbnailplugin-y-admin-generator-redimensionar-imagenes/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->