Carrierwave - Dynamic height/width and cropping - ruby-on-rails

So I got my Carrierwave Uploader which is pretty normal:
class ThumbFileUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process :resize_to_limit => [2000, 480]
end
In my model I got:
article.remote_thumbnail_url = article.picture_url
What I want to do is
Tell carrierwave the dimensions to use for scaling from within my model
Crop the image if it doesn't fit the exact dimensions after scaling
What's the best practice to accomplish that?

I have had exactly the same problem.
You basically need to have your model store the original image dimensions when the file is first uploaded. You can then use these with jCrop to control the cropping process.
My carrier wave uploaded as this function
def get_geometry
if (#file)
img = ::Magick::Image::read(#file.file).first
#geometry = [ img.columns, img.rows ]
end
end
You have to do rather a lot in the Model, the uploader and in your views.
A full write up is on my web site at the link below.
http://mark.stratmann.me/content_items/image-cropping-with-rails-3-2-carrierwave-bootstrap-modals-jcrop

Related

Carrierwave with MiniMagick is adding black background color to transparent .png when using remote_url with resize_to_[fit/fill/ect]

Expect the following Uploader, when I upload .png with no background via remote_XXX_url the :thumb version using a resize_to_fit is converted with a black background.
The original file uploaded is as the same as the original with the transparent background.
If I upload the image via a file_input the issue is not occurring.
Therefore I deduce that the issue is only occurring when doing a resize_to_XX transformation on remote_XXX_url file. Do you know what is happening ?
carrierwave (2.2.2) -- mini_magick (4.11.0) - The original image has a transparent background.
Image used : https://whirlpool-cdn.thron.com/delivery/public/thumbnail/whirlpool/pi-81b54ac7-7614-4a32-bdd1-a3f79db530d5/sckne7/std/320x320/859791401010.jpg?fill=zoom&fillcolor=rgba:255,255,255&scalemode=product
Thumb Image resized_to_fit
Image without resizing
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def store_dir
"#{ENV['AWS_S3_BUCKET_NAME']}/#{model.class.to_s.underscore}/#{model.id}"
end
def extension_allowlist
%w(jpg jpeg gif png svg webp)
end
version :thumb do
process resize_to_fit: [150, 150]
end
def filename
#name ||= "#{mounted_as}_#{timestamp}.#{file.extension}" if original_filename.present?
end
def timestamp
var = :"##{mounted_as}_timestamp"
model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
end
end
Your original file appears to have the extension .jpg but actually contains a PNG image.
ImageMagick itself is smart enough to spot that and it won't cause you any trouble. I don't know or use carrierwave but it appears to be carrying forward the original .jpg extension and forcing ImageMagick to write a JPEG which will make transparent regions black. I think it's this line:
#name ||= "#{mounted_as}_#{timestamp}.#{file.extension}" if original_filename.present?

Bad image quality with CarrierWave

I want to create the ability for the user to upload an image into a pdf which will be generated inside of the app. To do so I'm using gem prawn to pdf creation and CarrierWave::MiniMagic to create thumbnail versions of images for a Rails 6 app, and I've noticed loss of quality when the images are downsized.
original image:
the same image inside of pdf:
Such a bad quality is not acceptable for me. I don't know if it's a common problem but I've found a few posts without any resolution, is there any alternative solution/tool to handle it? I have been struggling with this problem for weeks.
I don't have nothing special in my uploader file:
class LogoUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
EXTENSION_WHITELIST = %w[jpg jpeg png].freeze
storage :file
process convert: 'png'
version :thumb do
process resize_to_fit: [300, 300]
end
def extension_whitelist
EXTENSION_WHITELIST
end
end

Rails Carrierwave & Imagemagick, using conditions to resize image

I have been struggling to find any tutorial or question that explains how to upload image and resize it according to certain conditions provided by user.
I am easily able to upload and resize image using hard coded values, however I am stuck at using user provided parameters to be accessed from the Uploader.
I want the image to be resized to either 800x600 or 300x300 based on whether the user checks the image as Large or Small.
For that I have a boolean column named "large" in the model structure.
In the Uploader I am able to access model and its values easily in the store_dir block, but anywhere outside this block any model attribute returns as nil.
This is what I want to do:-
class BannerUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
resize_to_fit(800,600) if model.large==true
resize_to_fit(300,300) if model.large!=true
end
However this returns the error
undefined local variable or method `model' for BannerUploader:Class
How to go about this issue.
To process an original file you can specify custom method:
class BannerUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process :process_original_version
def process_original_version
if model.large
resize_to_fit(800,600)
else
resize_to_fit(300,300)
end
end
end
For a specific version:
class BannerUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :normal do
if model.large
process resize_to_fit: [800,600]
else
process resize_to_fit: [300,300]
end
end
end
Ok so #Alex Kojin has the right answer. However I was faced with another problem as well. When the user submitted the form, the image would be resized always as small (300x300) because for some reason the image resize process would be executed first and then the "large" attribute would be set as true. Therefore the Uploader would always get model.large as false.
So this is how I had to change my action controller
def create
#banner=Banner.new
#banner.large=params[:large]
#banner.update_attributes(banner_params)
#banner.save
redirect_to :back
end
Not sure if this is the right approach but does work for me.

Upload image default image to s3 with carrierwave

We are using carrierwave gem to upload our images on a rails project.
We need to support the creation of the object without an image, but the application will run on several platforms and we don't want to support objects without images in everyone o that platforms, so we want to have a default image.
So this was the first solution
class IconUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def store_dir
"uploads/#{model.id}"
end
def default_url
"/images/icons/" + [version_name, "default.png"].compact.join('_')
end
version :thumbnail do
process resize_to_fill: [200, 200]
end
version :high_resolution do
process resize_to_fill: [400, 400]
end
end
The problem with this is that all the devices will come to the server (not to S3) looking for that default image.
At the same time its a problem with the multiple versions of the image.
So this second solution came:
class CategoryController < ApplicationController
...
def create
#category = Category.new(category_params)
#uploader = IconUploader.new(#category, :icon)
uploader.cache!(File.open("app/assets/images/photos/picture.jpg"))
#category.image=#uploader
#object.save
end
...
end
This solves the problem of the multiple resolutions and it always goes to S3 to get the image. But the problem here is that it will duplicate the default image on S3 many times.
Our third solution could be a to use an already created image on Amazon as default URL, but it has the same problem with the version so we don't even implement it.
Can any one think of a better solution for this problem?

Duplicating Carrierwave images makes them darker?

I have an Event model that has many photographs. I have an image uploader mounted to the Photographs attribute, and regular uploads and everything is working fine.
However, when I try and duplicate an event, recreating a new photograph object for the new event, the new image is darker than the original, and if I duplicate the duplicate event, it gets darker still.
I have played around with it, but have no solution.
My Uploader code:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
include CarrierWave::Processing::RMagick
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def cache_dir
"#{Rails.root}/tmp/carrierwave"
end
process :colorspace => :rgb
# Remove EXIF data
process :strip
# Create different versions of your uploaded files:
version :thumb do
process :resize_to_limit => [640, 640]
end
version :preview_thumb do
process :resize_to_limit => [600, 600]
end
version :wine_thumb do
process :resize_to_limit => [160, 440]
end
version :logo_thumb do
process :resize_to_limit => [90, 90]
end
end
And my duplcation code (in Active Admin):
member_action :create_duplicate_event, method: :post do
old_event = Event.find(params[:id])
photograph_urls = old_event.photographs.map(&:image_url)
attributes = old_event.attributes.except("photographs", "id")
new_photos = []
photograph_urls.each do |photo|
new_photo = Photograph.new({
remote_image_url: photo
})
if new_photo.save
new_photos << new_photo
end
end
#event = Event.new(attributes)
#event.photograph_ids = new_photos.map(&:id)
render "/admin/events/_events_form/"
end
The :rgb tag was an attempt to fix. But no luck.
Ruby 2.1 and Rails 4.0
Ok, after a lot of playing around and searching I managed to fix this problem.
First, you need to download the .icc color profiles, which can be found here. It says for windows but they seemed to work for me on my Mac.
Once you have put the .icc files into a /lib/color_profiles directory, add the following code to your uploader:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
process :convert_image_from_cmyk_to_rgb
#versions, and any other uploader code go here
def convert_image_from_cmyk_to_rgb
manipulate! do |image|
if image.colorspace == Magick::CMYKColorspace
image.strip!
image.add_profile("#{Rails.root}/lib/USWebCoatedSWOP.icc")
image.colorspace == Magick::SRGBColorspace
image.add_profile("#{Rails.root}/lib/sRGB.icc")
end
image
end
end
end
This converts CMYK images to RGB, and keeps the profiles keeping nice, while keeping RGB images as they were, and not ruining them.
I hope this helps someone in the future, and saves them the hours I spent working this out.

Resources