Minimagick不减少png文件大小而是增加

时间:2020-07-28 12:00:46

标签: ruby-on-rails amazon-s3 carrierwave ruby-on-rails-6 minimagick

我只想在将图像上传到s3存储桶之前压缩图像的大小大于200kb,如果我的图像未与任何模型连接,我将使用aws存储直接将其上传到s3

我的上传器是

class CoverImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  #include CarrierWave::RMagick
  
  include CarrierWave::MiniMagick
   process :compress_image, if: :size_is_large?

  # Choose what kind of storage to use for this uploader:
  storage :aws
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def initialize(location_id)
    @location_id = location_id
  end


  def store!(*args)
    super
    @file
  end

  def store_dir
    "uploads/cover-images/#{@location_id}"
  end

  def compress_image
    manipulate! do |img|
      img.quality("60")
      img
    end
  end

  def size_is_large? picture
    image = MiniMagick::Image.new(picture.path)
    (image[:size]/1000) > 200
  end
end

我正在使用以下代码上传图片

image = MiniMagick::Image.open(https://abc.s3.amazon.com/uploads/image.png)
              image_type = image.type.downcase
              image_name = "#{location}.#{image_type}"
              image_path = Rails.root.join("tmp", image_name)
              file = File.open(image_path, 'wb') do |output|
                 output.write RestClient.get(cover_image["url"])
                 output.path
               end
               uploader = CoverImageUploader.new("test123")
               s3_path = File.open(file) do |file|
                          uploaded_image = uploader.store!(file)
                          uploaded_image.url
                        end


对于jpg和jpeg,上面的代码可以正常工作,但是对于png图像,不是减小尺寸,而是增大图像尺寸 我的文件大小为602 kb(png),但在上传到s3后增加到1.3 mb 我希望对其进行压缩,以便图像可以更快地加载到我们的网页上。 谁能建议我该怎么压缩png图像?

0 个答案:

没有答案
相关问题