Using RMagick/ImageMagick in Rails to resize images

ImageMagick is, as you may already know, a software suite used to read, create and convert images. At this point, you may have already noticed the potential of ImageMagick in combination with Rails to read, resize, rotate, generate captchas... you name it.

The connection between ImageMagick and Rails is done using a gem called RMagick. You can take a look at the User's Guide/API here: RMagick User's Guide. As many of the other Rails developers around, I use a Mac to develop my applications, and then I deploy them in a Linux server. As the Mac installation is perhaps a bit trickier, I'm describing it too.

Installing ImageMagick/RMagick in MacOS X

If you don't have imagemagick already installed, the easiest way to do so is using MacPorts (formerly DarwinPorts). You can follow the instructions on the MacPorts site: Installing MacPorts.
Once you have MacPorts installed, you can easily install ImageMagick issuing the following command in your Terminal (you will be asked for your password):

macbookpro:~ daniel$ sudo port install imagemagick

Now, I'm supposing you already have RubyGems installed.
If not, download the source from RubyForge, compile it with ./configure; make and install it with make install.

So, we can proceed to install the RMagick gem. The tricky part is that you need to set some environment variables to point to the place where the ImageMagick binaries are installed. Open your Terminal, and set the environment variables copying and pasting the following lines:

export MAGICK_HOME=/usr/local/ImageMagick/
export DYLD_LIBRARY_PATH="$MAGICK_HOME/lib/"
export PATH="$MAGICK_HOME/bin:$PATH"


You can now issue the gem install rmagick command which will download, compile and install the RMagick gem automatically.

Installing ImageMagick/RMagick in Linux

The installation under Linux is much easier than in MacOS X. Install ImageMagick and development libraries first and then install the gem (and rubygems too, if you don't have it - apt-get install rubygems -).

newton:~# apt-get install imagemagick libmagick9-dev
newton:~# gem install RMagick

Once you have installed RMagick, using it in your Rails application is as easy as adding the line require 'RMagick' in the controller you need RMagick.

In the following example, we create the preview action in our controller, which will, in a simple way, resize any image to a maximum of 200x200.

def preview
  @archive = Archive.find(params[:id])
   if @archive.contenttype == "image"         
      img_orig = Magick::Image.read("/my/picture/path/"+@archive.filename).first
      img = img_orig.resize_to_fit(200,200)
     @response.headers["Content-type"] = img.mime_type
      render :text => img.to_blob   
   end
end

We could use now this action we created to access the image from another view:
    <img src="/archives/preview/<%= @archive.id -%>">

You can take a look at the API to see the complete list of transformations you can do with RMagick: RMagick User's Guide



 

How do you put a giraffe into a refrigerator?

Today I stumbled upon (via Igor's blog) a quite interesting and strange bunch of questions that are supposed to be useful to decide if someone will be a good consultant. I must say I only got right questions 2 and 3. Post your results in a comment if you want to.

Q1. How do you put a giraffe into a refrigerator?

The correct answer is: Open the refrigerator, put in the giraffe, and close the door.

This question tests whether you tend to do simple things in an overly complicated way.

Q2. How do you put an elephant into a refrigerator?

Did you say, Open the refigerator, put in the elephant and close the refrigerator?

Wrong Answer

Correct Answer: Open the refrigerator, take out the giraffe, put in the elephant and close the door.

This tests your ability to think through the repercussions of your previous actions.

Q3. The Lion King is hosting an animal conference. All the animals attend… except one. Which animal does not attend?

Correct Answer: The elephant. The elephant is in the refrigerator.

You were the one who just stuffed the elephant into the refrigerator.

This tests your memory.

Okay, even if you did not answer the first three questions correctly, you still have one more chance to show your true analytical abilities.

Q4. There is a river you must cross but it is used by crocodiles, and you do not have a boat. How do you manage it?

Correct Answer: You jump into the river and swim across. Have you not been listening? All the crocodiles are attending the Animal Meeting.

This tests whether you learn quickly from your mistakes.


According to a consulting firm using this test, approximately 90% of the professionals tested answered incorrectly but many preschoolers answered several answers correctly.

One conjecture: most professionals don’t have the analytical powers of a four-year-old.



 

Improving performance in Rails with Apache2

The standard Apache2 installation shipping with most Linux distributions uses MPM prefork. While this is a good model, for instance, when using apache modules to run PHP, it does not perform that well when running Rails using FastCGI. Instead, we can use MPM Worker for a better performance.

So, what's the difference between prefork and worker?

Quoting from the Apache MPM Prefork page:
MPM Prefork implements a non-threaded, pre-forking web server that handles requests in a manner similar to Apache 1.3.

And for the Apache MPM Worker says:
MPM Worker implements a hybrid multi-process multi-threaded server. By using threads to serve requests, it is able to serve a large number of requests with less system resources than a process-based server.

So, you have decided you want to switch to Apache2 MPM Worker. One of the problems you may find when doing an apt-get install apache2-mpm-worker is that dpkg will automatically delete the PHP module and other packages associated to it. The solution is to let dpkg remove PHP and install it by ourselves.

We will have to install some build-related packages if they were not installed before:
persefone:~# apt-get install build-essential flex libxml2-dev

Installing apache2-mpm worker:
persefone:~# apt-get install apache2-mpm-worker (will remove mpm-prefork, and libapache2-mod-php and related packages)

We need to install libmysqlclient development headers to compile PHP with mysql support:
persefone:~# apt-get install libmysqlclient15-dev

We also need apxs2, so we will install the apache2 development headers for mpm worker:
persefone:~# apt-get install apache2-threaded-dev

We can download the PHP source code from http://www.php.net/downloads.php and compile it as usual:
persefone:~# ./configure --with-apxs2=/usr/bin/apxs2 --with-mysql --enable-maintainer-zts --prefix=/usr
persefone:~# make
persefone:~# make install

There is no need to make a symbolic link at /etc/apache2/mods-enabled/ for php5 now, as it is automatically enabled.



 

Install Instiki in Apache using FastCGI

Instiki is a Wiki clone made in Ruby on Rails really easy to setup and use. However, the installation manuals on the Instiki page are based in using WEBrick and not Apache.

The first step, is, of course, to download the Instiki tarball package in http://rubyforge.org/projects/instiki/. The most recent version available for now is 0.11.

As usual, we untar the package, renaming the directory to instiki:
persefone:/var/www# tar xvfz instiki-0.11.0.tgz
persefone:/var/www# mv instiki-0.11.0 instiki

Set up the permissions for the apache user:
persefone:/var/www# chown www-data:www-data instiki/ -R

On instiki/public, we need to edit the first line of the dispatch.fcgi file, changing:
#!c:/ruby/bin/ruby
with:
#!/usr/bin/ruby (the most common place where the ruby binary is located)

We will also need to modify the .htaccess file in the same directory. You'll have to search for the line:
RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

replacing it with:
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

If you use mod-fcgid instead of mod-fastcgi, you will have to change the following line too, in .htaccess:
AddHandler fastcgi-script .fcgi
replacing it with:
AddHandler fcgid-script .fcgi

We should define a MySQL database too (by default sqlite will be used), editing database.yml under instiki/config

production:
  adapter: mysql
  host: localhost
  database: instiki
  username: instiki
  password: myinstikipassword
  socket: /var/run/mysqld/mysqld.sock


We usually will set up a new hostname for the wiki
persefone:/etc/apache2/sites-available# vim wiki.example.com

<Directory /var/www/instiki/public>
    Allow from all
    AllowOverride all
</Directory>

<VirtualHost *>
    ServerName wiki.example.com
    DocumentRoot /var/www/instiki/public/
</VirtualHost>


And we enable it making a symbolic link from sites-available to sites-enabled

persefone:~# ln -s /etc/apache2/sites-available/wiki.example.com /etc/apache2/sites-enabled/

Under the Instiki directory, we will generate the initial database with the following command (RAILS_ENV=production tells rake to generate the production database) :
persefone:/var/www/instiki# RAILS_ENV=production rake migrate

We can now reload Apache2 and Instiki should be working.



 

Marte habitable en 1000 años?

Encuentro vía Digg un artículo que me ha parecido muy interesante sobre la posibilidad de hacer Marte habitable en 1000 años, al contrario que propuestas anteriores, que estimaban el tiempo necesario en unos 20000 o 100000 años.



Según Robert Zubrin (Mars Society), la colonización tendría lugar en 3 pasos, de los cuales el primero ya ha empezado: la exploración del planeta, para descubrir minerales, depósitos de hielo y posibles hábitats. El paso siguiente será construir bases y finalmente, deberá establecerse una colonia autosuficiente.

Paso 1: Terraforming (o convertir Marte en la Tierra)

Estima que el año en el que podrá empezarse la transformación a un hábitat similar al de la Tierra será el 2150. El primer paso será calentar Marte, para lo que prevé tres posibles opciones:

Opción A: Espejos en órbita

Calentar la atmósfera a más de 40ºC (la temperatura en el ecuador ronda los 0ºC en algunos puntos), usando una serie de espejos gigantes (de 120km de diámetro), para dirigir los rayos solares a puntos específicos de la superfície de Marte donde pueda haber gases o agua.




Opción B: Asteroides
Los asteroides son esencialmente contenedores helados de gases invernadero. Si se pudiera dirigir un asteroide, colisionando con Marte, la energía producida por el impacto sería suficiente para fundir un trillón de toneladas de agua, y la cantidad de amoníaco desprendida por el asteroide podría aumentar la temperatura casi 3ºC. Zubrin cree que el impacto de 40 asteroides podría hacer la atmósfera de Marte habitable. El problema es que se tardaría demasiado tiempo en dirigir el asteroide y esperar al impacto, y que crearía problemas para los habitantes.



Opción C: Calentamiento global
De forma similar a lo que ocurre en la Tierra (pero a larga escala), provocar un calentamiento global con tetrafluorometano (CF4), usando 5000MW (con 5 plantas nucleares), para emitir 1000 toneladas de gas por hora durante 30 años, para aumentar la temperatura en 10ºC.



Paso 2: Liberar gases del suelo

El suelo marciano contiene grandes cantidades de CO2 de la época (hace 3 billones de años) en la que Marte tenía una atmósfera de dióxido de carbono. El dióxido de carbono se podría liberar al aumentar la temperatura, haciendo que el CO2 liberado de la tierra aumente la temperatura otros 10 grados en 20 años, consiguiendo evaporar algo de hielo y creando los primeros indicios de tiempo. Marte entonces tendría 0.10 atm de CO2 en el año 2200 (50 años después de empezar el proceso).



Paso 3: Tiempo para plantar

En el 2250, la atmósfera sería 1/5 de la de la Tierra (0.21 atm, con 0.20 atm de CO2). Los residentes podrían caminar sin necesidad de trajes (aunque necesitarían oxígeno). Sería posible empezar a plantar, usar aviones y constuir ciudades (cerradas en forma de cúpula para optimizar el oxígeno).

En el momento en el que en el ecuador se consiga una temperatura constante de más de 0ºC, se conseguiría agua líquida y se podría empezar a plantar, aunque debería empezarse con bacterias fotosintéticas y líquenes.




Paso 4: La estación de la recogida

En el momento en que las plantas empiecen a crecer, convertirán el CO2 de la atmósfera en oxígeno. Pero no podrá hacerse como en la Tierra, donde se deja a las plantas muertas descomponerse, ya que generaría CO2, ralentizando el proceso. Zubrin cree que la solución estará en la recogida rápida de plantas y destrucción de basura usando un proceso complejo de fertilizado, aunque también comenta la posibilidad de modificar genéticamente las plantas para producir más oxígeno.


Paso 5: Esperar 1000 años

Una vez pasados los 50 años para generar la atmósfera y otros 50 para poder caminar por Marte, se tardará alrededor de 1000 años en producir suficiente oxígeno por parte de las plantas para poder respirar libremente. Durante esos 1000 años, los residentes deberán plantar y recoger, jugando el papel de la naturaleza para hacer más rápida la conversión de la atmósfera de CO2 a oxígeno.





Artículo original:
Hijacking the Red Planet (Popular Science)



 

Microsoft's answer to the iPhone

One day after the presentation of the iPhone in the MacWorld Expo, Microsoft announces they will be launching their new zunePhone, in a similar size and style as in the Zune music player.

The commercial follows:


Awesome!



 

Apple releases iPhone

Finally, we have iPhone for a whopping $499 on a two-year contract (guess how much network-free). Steve has presented it at his MacWorld's Keynote. He has also presented iTV, as expected, a TiVo like device, to stream content to your TV (also wirelessly).



Nice looking shape, and no buttons. The screen is a touchscreen, with an accelerometer, and you can scroll on the screen with two fingers like in your MacBook Pro.




The iPhone is a quad-band (850/900/1800/1900) GSM+EDGE (and they say it's not 3G). But it has Bluetooth and Wireless. The phone that Steve was showing has a 8GB hard drive.



It has an embedded push-IMAP client like Blackberries (offered by Yahoo, Steve says)



And you can surf the web quite nicely. Based on Safari. He also shows some more pages, like Amazon, and Google Maps. Some widgets, too.



I don't know what you'll do, but I am completely going to buy one.

More information:
Engadget: Live from MacWorld 2007
HardMac: Events
Engadget: The Apple iPhone runs OSX



 

January in Geneva

Flying through the Alps at about 7:30am to Geneva on Clickair. Clickair is the new low-cost company from Iberia, in my opinion, much better than Easyjet. The only bad thing, though, is that they also use the free allocation of seats thing, which makes people run like mad to the boarding doors to get the best seats.



From Bel-Air, with the Alps and the St. Pierre Cathedral at the end, with great weather (2-5 degrees, no rain).



Geneva at night. Isn't it beautiful?



From the Pont des Bergues, with L'Île at the right and the Rue du Rhône at the other side, with a nice light Christmas tree at the Dresdner Bank building.



Nice effect with clouds and lighting, with L'Île at the front.


From the Quai du Mont-Blanc. I must say I'm quite impressed by the quality of the pictures I made at night. Just used a Lumix FX-01 and the genevoise ponts for long exposure support.





 

Entrevista en el blog de Manuel Sagra

Hace unos días, Manuel Sagra me comentó la posibilidad de hacerme una entrevista para hablar sobre in.solit.us en su blog. Con mucho gusto accedí a ello, y recientemente la ha publicado en su blog.

Os recomiendo echarle un vistazo, no sólo a la entrevista, en la que se cubren aspectos interesantes sobre in.solit.us, sino al blog de Manuel en general.

Entrevista a Daniel Álvarez, creador de in.solit.us



 

Merry Christmas - Feliz Navidad




Like every year, I'm writing this post to wish you a merry Christmas and happy new year. Hope to see you around again next year. Have fun!

As a mere curiosity, the last year Christmas' post is the most read post in the blog (86987 views), without any apparent reason. So let's try to beat the record next year ;)



Como cada año, escribo este post para desearos una feliz Navidad y un muy feliz año nuevo. Espero seguir viendoos por aquí el próximo año. Disfrutad de la Navidad.

Curiosamente, el post de Navidad del año pasado es el post más leído de todo el blog (86987 vistas), sin ninguna razón aparente. Así que intentemos batir el record el próximo año ;)




 

Search



About

newton.gra2.com is a blog about technology, opinion and random thoughts written by Daniel Alvarez, a computer engineer currently living in Zurich, Switzerland.

Topics

News (20/0)
Manuals (24/0)
Security (7/0)
Music (3/0)
Weeklog (1/0)
Personal (34/0)
Photos (3/0)
Opinion (14/0)
Windows (5/0)

Blogroll

Pros i contres (Jordi)
Entrepa de fusta (Oriol)
Spaghetti Code (Isaac)
Made in net (Eric)
Nogare (Juan)
Blog de Isaac Jimenez
Web d'en Jaume Benet
Montcada Wireless (Fran)
Blog d'en Ricard Forniol
Angela Fabregues
in.solit.us

Libertad Digital
FOX News
The Wall Street Journal
The Washington Times
The Jerusalem Post

Michelle Malkin
Eurabian News
Nihil Obstat
Barcepundit
Expose the left
Davids Medienkritik
Johan Norberg
Ayaan Hirsi Ali

User Functions

:

:


Lost your password?

Latest posts

Stories

No new stories

Comments last 2 days

No new comments

Trackbacks last 2 days

No new trackback comments

Links last 2 weeks

No recent new links