", :medium => "-6ren">
gpt4 book ai didi

ruby-on-rails - 检测文件类型并调整图像大小

转载 作者:行者123 更新时间:2023-12-02 16:57:53 25 4
gpt4 key购买 nike

我有支持 pdf 和图像的模型附件。如何检测它的图像,然后才调整它的大小?当它是回形针时,一切都很简单。但现在 ? ;)

class Attachment < ActiveRecord::Base

has_attached_file :attachment,
styles: lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"} : {:thumb => { :geometry => "100x100#", :format => 'jpg'}, :medium => { :geometry => "300x300#", :format => 'jpg'}}},

def is_image?
attachment.instance.attachment_content_type =~ %r(image)
end

end

如何使用事件存储制作类似上面的内容?我这样尝试:

class Attachment < ApplicationRecord
has_one_attached :file
validates :file, presence: true

def file_url
if ???? (is image?)
rails_blob_url(file.variant(resize: '1920x1920').processed)
else
rails_blob_url(file)
end
end

最佳答案

ActiveStorage 内置了流行内容类型的帮助程序,例如:图像、视频、音频等。图像是 image?:

if file.image?
rails_representation_url(file.variant(resize: '1920x1920').processed)
else
rails_blob_url(file)
end

API 文档:https://api.rubyonrails.org/classes/ActiveStorage/Blob.html#method-i-image-3F

音频?图片?文本?视频?

关于ruby-on-rails - 检测文件类型并调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55645566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com