Search code examples
ruby-on-railsimagepaperclipcolor-space

Validate Image Colorspace With Paperclip


I'm using Paperclip to convert images. I have noticed a severe degradation of quality of the produced image if its colorspace isn't set to srgb.

Is there a way to validate the colorspace of the uploaded image?


Solution

  • Ive got half an answer that might help...

    You will need to install: https://github.com/rmagick/rmagick

    Add to your model:

    attr_accessor :image_colorspace
    validates_exclusion_of :image_colorspace, in: [Magick::CMYKColorspace], message: 'is not RGB'
    before_logo_post_process :read_image_colorspace
    def read_image_colorspace
      self.image_colorspace = Magick::Image.from_blob(image.queued_for_write[:original].read).first.colorspace
      true
    end
    

    (Replace image with your attachment name.)

    ...or, if you prefer to not use rmagick, and you have a 'nix system, you could do this:

    attr_accessor :image_colorspace
    validates_exclusion_of :image_colorspace, in: ['CMYK'], message: 'is not RGB'
    before_logo_post_process :read_image_colorspace
    def read_image_colorspace
      self.logo_colorspace = `identify -verbose %m "#{image.queued_for_write[:original].path}" | grep 'Colorspace'`.to_s.upcase.strip.split(' ').last
      true
    end