Search code examples
cssruby-on-railsruby-on-rails-3image-processingcrop

Crop and resize image - Is it possible to use <%= image_tag %> for setting a background-image?


In this project users can upload an image to a post. This image should be displayed with a fixed height and 100% width.

So the image has to be cropped depending on the image size of the upload.

I would like to use a CSS only solution like here http://jsfiddle.net/tx7sf/90/ where the image is integrated as a background-image in order to crop the image.

html:

<div class="thumb" style="background-image: url('http://24.media.tumblr.com/tumblr_ly7xjxn3QI1r62v9yo1_1280.png');"></div>

css:

.thumb {
    display: inline-block;
    width: 100%;
    height: 400px;
    margin: 5px;
    border: 3px solid #c99;
    background-position: center center;
    background-size: cover;
}

Here comes my newbie question:

In the fiddle example above there is a fix URL for the image, but I have to use depending on the upload something like this:

<%= image_tag @post.image.url(:fullscreen), :class=> "imagearea", :id=> "img_prev" %> 

Is it possible to use an image_tag like above for such an CSS background-image integration?

How could I do this? Or does this make no sense at all?

Thank you so much for your help! Really appreciated!

UPDATE:

A little more specific: I want to use this image inside a form which looks something like this:

<%= simple_form_for @post do |f| %>

 <%= image_tag @post.image.url(:fullscreen), :class=> "imagearea", :id=> "img_prev" %> 
   <div class="container"> 
              <h1> <%= f.text_area :title, 
                  :class => "imagefield", 
                  :rows => 1,
                  :placeholder => 'Enter your Title.',
                  :maxlength=>"48" %>
              </h1>
    </div>
    <div class="addpicture">
      <input href="#" id="post_image" name="post[image]" type='file'  onchange="readURL(this);" />
    </div>

<% end %>

Thanks again!


Solution

  • Look at image_path.

    <div class="thumb" 
      style="background-image: url('<%= image_path(@post.image.url(:fullscreen) %>');"></div>
    

    http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-image_path