Ruby如何旋转图片和获取图片的Retate值?

这是一个常见的需求,有时候我们有手机拍摄的图片,在网页上显示,会倒立。所以,需要将图片旋转90度。

比较常用的一种方案是:exiftool

http://www.sno.phy.queensu.ca/~phil/exiftool/#top


  • 下载
    http://www.sno.phy.queensu.ca/~phil/exiftool/Image-ExifTool-8.98.tar.gz

  • install
      perl Makefile.PL
      make
      make test
      sudo make install
    

  • 安装gem
    http://miniexiftool.rubyforge.org/
    gem install mini_exiftool

  • 运行测试脚本
    exif = MiniExiftool.new("shu_bak.jpg", :numerical => true);
    exif.orientation = 1 # 1 normal, 6 un_normal 90 cw
    exif.save


  • 但是以上的方法 得出来的图片,在网页上显示,仍然不是正立的。所以,我们改用mini_magick

    image = MiniMagick::Image.open("input.jpg")
    image.combine_options do |c|
      c.rotate "90>"
    end
    image.write "output.jpg"

    如何判断图片是否正常呢?
    1.9.2-p320 :009 > image["exif:orientation"]
     => "6" 
    
    如果为6,说明图片是倒立的 :)



  • 补充说明
    Iphone浏览器 能识别 orientation信息,所以, 当我们将图片 rotate 90 度后, IPhone浏览器中显示的图片,反而会倒立。
    所以,需要完全适用所有的图片的方案,是上面两个方法的整合
    参考代码
      def change_image_rotate
        mobile_path = self.file.url(:mobile)
        file_path = File.join(Rails.root, "public", mobile_path)
        if image["exif:orientation"] == "6" 
          image = MiniMagick::Image.open(file_path)
          image.combine_options do |c| 
            c.rotate "90>"
          end 
          image.write(file_path)
          exif = MiniExiftool.new(file_path, :numerical => true);  
          exif.orientation = 1   
          exif.save  
        end 
      end 

  • 实际项目中的代码参考

  def change_image_rotate
    mobile_path = self.file.url(:mobile)
    file_path = File.join(Rails.root, "public", mobile_path)
    image = MiniMagick::Image.open(file_path)
    if image["exif:orientation"] == "6" 
      image.combine_options do |c| 
        c.rotate "90>"
      end 
      image.write(file_path)
      exif = MiniExiftool.new(file_path, :numerical => true);  
      exif.orientation = 1   
      exif.save  
    end 
  end 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值