How can I request an image and return it as black and white in rails?
I'd like to have an image and a combo box with 2 options: color, and black and white. When the combo box selection changes, I'd like to return the image as black and white and have this done dynamically on the server (so I don't have to store the black and white image on the server).
I was thinking I could point the im开发者_开发百科g tag at a url like "/images/blackandwhite/120" where 120 is the image id of the color picture, and have it dynamically turn the image to black and white and return the image data to the browser.
Is this possible? How would I do this?
Storing two copies of the image will be much more efficient than processing the image everytime it is requested.
However, you might be able to get away with using CSS image filters:
filter:gray
Paperclip, by default, is prepared to "alter" images. The objects used for modifying the images are called "processors". Paperclip comes with just one processor, for making thumbnails.
Processors don't do what you want; they "process" the image "once", when the original image is loaded. They require the "processed" images to be stored permanently. If you erase the images, they don't re-create them; they throw an exception.
However, by looking at the source code you can learn how to do what you want.
Here's the relevant code that makes the thumbnails). As you can see, it simply calls "convert" (the Imagemagick command) with certain parameters.
This should point you in the right direction. For example: You could create a method in your model that creates the black and white version of your image inside /tmp/
, and probably another one for deleting it. Your controller would have to call the former, send the image, and then delete the file.
There are several options in creating black and white images with Imagemagick - for example, you can create "real" black and white (2 colors only) or grayscale images. This forum post details the Imagemagick commands for several options.
Finally, a suggestion. If instead of this
/images/blackandwhite/120
Consider using this:
/images/120?color=blackandwhite
This way, you will not have to add additional routes, and your controller will be more restful. Then, on your show
action, you just have to check whether param[:color]
equals "blackandwhite"
精彩评论