CarrierWave / MiniMagick not updating file extension after convert

446 Views Asked by At

I'm using MiniMagick with CarrierWave to process some images on a Rails 5.2 app. My goal is to convert the original image to jpg, and create two other versions (resized).

My issue is that while the "versions" are correctly processed, the original file is converted but its extension is not updated to .jpg. For example, if I pass this image through my uploader, I will get the following three images: placeholder-image.png, large_placeholder-image.jpg and thumb_placeholder-image.jpg(note how the first image, which is the original one, still has an extension of .png).

I cannot figure out why this is happening, any help would be appreciated

Code below:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process convert: 'jpg'

  version :large do
    process resize_to_fit: [2000, 2000]
  end

  version :thumb do
    process resize_to_fit: [500, nil]
  end
end

Also tried this, resulting in the same issue:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :jpg do
    process convert: 'jpg'
  end

  version :large, from_version: :jpg do
    process resize_to_fit: [2000, 2000]
  end

  version :thumb, from_version: :jpg do
    process resize_to_fit: [500, nil]
  end
end
2

There are 2 best solutions below

0
benj-p On BEST ANSWER

I have solved this issue using version name customization. Note that I have chosen not to convert the original file, which is a bit different from my initial approach.

Here's a snippet of the code I've implemented:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :large do
    process resize_to_fit: [2000, 2000]
    process convert: 'jpg'

    def full_filename(for_file = model.file_name.file)
      "large_#{for_file.sub('png', 'jpg')}"
    end
  end

  version :thumb do
    process resize_to_fit: [500, nil]
    process convert: 'jpg'

    def full_filename(for_file = model.file_name.file)
      "thumb_#{for_file.sub('png', 'jpg')}"
    end
  end
end
1
mylescarrick On

don't know if you're still stuck, but the trick is that you need to override the filename method.

Something like

process convert: 'jpg'
    
      
def filename
  super.chomp(File.extname(super)) + '.jpg' if original_filename.present?
end

The other approach (that I'm about to try in my own app, and why I stumbled across your question here) is overriding it per-version – see https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Customize-your-version-file-names