Archer
Archer

Reputation: 1124

Rails paperclip image size depending on device size

I'm using paperclip in my rails application for uploading images. There are options to resize images.

has_attached_file :photo, styles: {large: '1000x1000>', medium: '500x500>'}

Is it possible to take the large image for large devices like iPad oder Full HD screen, and for mobile devices the medium sized image?

I'm implementing the images like that:

<div class="teaser" style="background: url(<%[email protected]_url %>)"></div>

Upvotes: 0

Views: 804

Answers (1)

Matt Gibson
Matt Gibson

Reputation: 14949

You have two options for this:

  1. Create multiple sizes when you save the image and reference them in the HTML
  2. Save it at the largest size and resize it on demand

For option 1, you can use the dynamic styles option in the paperclip settings.

Having said that, I recommend option 2. We use Imgix at my current employer and it's been an amazingly good option for us. You upload the largest image you have to S3 and then control its size using GET parameters e.g. httsp://yours3bucket.imgix.com/yourfolder/yourimage.png?width=205&height=354&hue=158 This has the enormous advantage of future-proofing your images as you don't need to regenerate them in different sizes if you change your mind about the resolutions you want - you just change the params in your HTML and Imgix sorts it out. You can also apply a load of dynamic effects like cropping the image, altering the colour balance etc. Only downside is it costs money, but depending on your use case, this could be very cost effective.

Either way, you then need to tell the browser to use the right size image. I'd recommend using srcset to do this, although IE still doesn't support it. This polyfill is a good option in the meantime.

Upvotes: 1

Related Questions