这是一个常见的需求,有时候我们有手机拍摄的图片,在网页上显示,会倒立。所以,需要将图片旋转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"
如何判断图片是否正常呢?
如果为6,说明图片是倒立的 :)1.9.2-p320 :009 > image["exif:orientation"] => "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