carrierwaveuploader / carrierwave

Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks
https://github.com/carrierwaveuploader/carrierwave
8.79k stars 1.66k forks source link

The file extension does not change after changing the file type in `minimagick!` #2714

Open gomo opened 10 months ago

gomo commented 10 months ago

I want to convert heic to jpg using Mini magick, but it seems that process convert: :jpg does not allow to specify quality, so I created a method and tried to convert it using minimagick!.

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

  process :convert_to_jpeg, if: :heic?

  def filename
    @secure_name ||= "#{SecureRandom.uuid}.#{file.extension}"
    @secure_name
  end

  private

    def heic?(new_file)
      new_file.content_type == 'image/heic'
    end

    def convert_to_jpeg
      minimagick! do |image|
        image
          .quality(80)
          .convert('jpg')
      end
    end
end

The file type is converted to jpg, but the filename extension remains heic.

CarrierWave::SanitizedFile(self.file)inconvert_to_jpegchanges both content_type and file extension to jpg, butCarrierWave::Storage:::Fileinfilename Fog::File(self.file)` is heic.

What I found strange is that converting with process convert: :jpg also changes the extension. It's pretty much the same as the convert source, but my method didn't change it. How can I change it?

https://github.com/carrierwaveuploader/carrierwave/blob/20c6d753f8720c63718de44595351086d71b15bd/lib/carrierwave/processing/mini_magick.rb#L101-L107

gomo commented 10 months ago

I forgot to write the versions.

thx

Ahsanfaiyaz123 commented 4 months ago

Solution for Handling HEIC Image Uploads with CarrierWave and MiniMagick

To address issues with displaying HEIC images after upload using CarrierWave, follow these steps to convert HEIC files to JPEG format during the upload process:

Update ImageUploader

Ensure HEIC is included in the list of allowed file extensions:

def extension_white_list
  %w(jpg jpeg gif png heic)
end

Implement Conversion Method

Add the following method to your ImageUploader to convert HEIC images to JPEG:

process :convert_heic_to_jpeg , if: :heic?

private

def heic?(file)
   file.content_type == 'image/heic' || file.extension.downcase == 'heic'
end

def convert_heic_to_jpeg
   cache_stored_file! unless cached?

   temp_path = current_path.sub(/\.\w+$/, '.jpg')
   image = MiniMagick::Image.open(current_path)
   image.format('jpg')
   image.write(temp_path)
   File.rename(temp_path, current_path.sub(/\.heic\z/i, '.jpg'))
end

Explanation

This solution ensures compatibility of uploaded HEIC images across various browsers and image processing tools by converting them to JPEG format.