Home > Mobile >  Resizing images with variant method creates broken image icon in Rails
Resizing images with variant method creates broken image icon in Rails

Time:12-20

I am new to rails and I am adding an avatar image to my app, but when I try to resize it in my ApplicationHelper using the variant method the image appears as a broken image icon, I don't understand why this is other than it might have to do with the pipeline

Here is a picture of whats happening: enter image description here

application_helper.rb

module ApplicationHelper
  require "mini_magick"

  def avatar_url_for(user, opts = {})
    size = opts[:size || 32]

    if user.avatar.attached?
      user.avatar.variant(resize_to_limit: [100, 100])
    else
      hash = Digest::MD5.hexdigest(user.email.downcase)
      "https://secure.gravatar.com/avatar/#{hash}.png?s=#{size}"
    end
  end
 end

_navbar.html.erb

<nav >
<div >
<a  href="#">Facebook</a>
<button  type="button" data-bs-toggle="collapse" data-bs- 
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- 
expanded="false" aria-label="Toggle navigation">
  <span ></span>
</button>
<div  id="navbarSupportedContent">
  <ul >
    <li >
      <a  aria-current="page" href= "/">Home</a>
    </li>

    <li >
    <a  aria-current="page" href= "users/<%= current_user.id 
%>"  >Profile</a>
  </li>

    <li >
    <a  aria-current="page" href="/pages/friends"><i ></i></a>
  </li>
    
    
  </ul>
  <ul  >
  
  <% if current_user %>
  
      <%= link_to user_path(current_user.id), class: "nav-link" do %>
    
    <%= image_tag avatar_url_for(current_user, size: 32), class: "rounded-circle mr- 
1" %>
 
    <% end %>

  </ul>

  <ul >
  Logged in as <%= current_user.username %>
  
<% end %>
</ul>

  <ul >
  
  <% if current_user %>
   
  <%= link_to(destroy_user_session_path, {:class => "nav-link", :method => :delete}) 
do  %>
    <span > Logout </span>
<% end %>
<% end %>
  
  </ul>

  <ul >
  
    <%= render 'layouts/notifications' %>
  
  </ul>

  <form  role="search">
    <input  type="search" placeholder="Search" aria- 
  label="Search">
    <button  type="submit">Search</button>
  </form>
</div>

CodePudding user response:

I needed to run sudo apt-get install libvips to add libvips dependencies that were missing.

The method #resize_to_limit is from the image_processing gem which relies on the ruby-vips gem which relies on having libvips installed.

CodePudding user response:

To resize images ActiveStorage uses third-party libraries, by default

  • libvips (in rails >= 7)

  • ImageMagick (in rails < 7)

To install on Mac

brew install imagemagick

or

brew install vips

On Ubuntu based OS

sudo apt install imagemagick

or

sudo apt install libvips

You also need in your Gemfile

gem "image_processing"

On Heroku there is no libvips package. To activate it you need create Aptfile with such content

libglib2.0-0
libglib2.0-dev
libpoppler-glib8
libheif-dev
libvips-dev
libvips
  • Related