2012-01-13 26 views
7

¿Cómo puedo obtener el ancho y la altura de la instancia actual de carrierwave?Dimensión de la imagen Carrierwave

Algo como esto:

car_images.each do | image| 
    image_tag(image.photo_url, :width => image.photo_width, :height => image.photo_height) 
end 

Desafortunadamente image.photo_width y image.photo_height no están trabajando. Necesito especificar el ancho y alto de las imágenes, se requiere en el plugin jquery que estoy usando.

Respuesta

13

Combinar https://github.com/jnicklas/carrierwave/wiki/How-to:-Get-version-image-dimensions y https://github.com/jnicklas/carrierwave/wiki/How-to:-Store-the-uploaded-file-size-and-content-type y se obtiene:

class Image 
    before_save :update_image_attributes 

    private 

    def update_image_attributes 
    if image.present? 
     self.content_type = image.file.content_type 
     self.file_size = image.file.size 
     self.width, self.height = `identify -format "%wx%h" #{image.file.path}`.split(/x/) 
     # if you also need to store the original filename: 
     # self.original_filename = image.file.filename 
    end 
    end 
end 
11

Usted puede salvar la altura y anchura que los atributos con su modelo con bastante facilidad si se utiliza RMagick. En el cargador Carrierwave:

class ArtworkUploader < CarrierWave::Uploader::Base 

    def geometry 
    @geometry ||= get_geometry 
    end 

    def get_geometry 
    if @file 
     img = ::Magick::Image::read(@file.file).first 
     geometry = { width: img.columns, height: img.rows } 
    end 
    end 

end 

Y en su modelo:

class Artwork < ActiveRecord::Base 

    mount_uploader :image, ArtworkUploader 

    before_save :save_image_dimensions 

    private 

    def save_image_dimensions 
     if image_changed? 
     self.image_width = image.geometry[:width] 
     self.image_height = image.geometry[:height] 
     end 
    end 
end 
+2

Esto funciona para nuevas cargas ('¿image_changed? == true'), pero ¿qué pasa con la medición de las dimensiones de los archivos adjuntos existentes? Parece que no puedo acceder al método 'get_geometry' desde la consola. Estoy obteniendo "' método privado 'file' llamado # # CarrierWave :: Storage :: Fog :: File: 0x00000005225b28> '". –

0

@ respuesta de JamieD trabajó para mí, con una excepción. Estaba usando MiniMagick.

Así que agregué algo como esto a mi cargador.

def geometry 
    @geometry ||= get_geometry 
end 

def get_geometry 
    if @file 
    img = ::Magick::Image::read(@file.file).first 
    geometry = { width: img.columns, height: img.rows } 
    end 
end 
+0

He actualizado https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Get-image-dimensions con información de MiniMagick. –

1

O simplemente usa FastImage. Esto hace que sea mucho más fácil medir los archivos adjuntos de forma retroactiva.

Cuestiones relacionadas