4

我正在尝试将图像保存到 Redis,稍后将在 Resque 任务中获取并上传到我们的图像服务器。

ImageHandle 类将为我们获取图像。目前,我只关心从 Redis 中获取图像。

class ImageHandle < ActiveRecord::Base
  attr_accessible :uploaded, :image
  after_save :save_image

  def image_data
    $redis.get(redis_key)
  end

  def image=(value)
    @image = value
  end

  private

  def redis_key
    @redis_key ||= "image_handle:#{id}:image"
  end

  def save_image
    $redis.set(redis_key, @image.read)
  end
end

$redis 在初始化程序中设置的位置:

$redis = Redis.new

这是我的测试文件:

require 'test_helper'

class ImageHandleTest < ActiveSupport::TestCase
  include ActionDispatch::TestProcess

  setup do
    clear_redis
  end

  test 'saves an image' do    
    image = fixture_file_upload('screaming-eagle.jpg', 'image/jpg')
    # You can only read from a file fixture once
    same_image = fixture_file_upload('screaming-eagle.jpg', 'image/jpg')

    image_handle = ImageHandle.create(image: image)

    expected = same_image.read
    actual   = image_handle.image_data

    puts "length of expected: #{expected.length}"
    puts "length of actual:   #{actual.length}"

    assert_equal expected, actual
  end
end

结果是:

length of expected: 81500
length of actual:   78524
F 

Finished tests in 0.270385s, 3.6984 tests/s, 3.6984 assertions/s.

  1) Failure:
test_saves_an_image:23

我不知道是怎么回事。

当我尝试设置 ("b" * 81500) 然后获取它时,我将其恢复为预期的 81500 长度。

感谢你给与我的帮助。

4

2 回答 2

3

redis-rb 将字符串转换为默认的外部编码Encoding::default_external,通常是 UTF-8。见https://github.com/redis/redis-rb/commit/61fa1f884a643cd7dea8e0e56498860594058a39

您可以在存储二进制数据之前将它们编码为 Base64,并在检索后从 Base64 解码:

class ImageHandle < ActiveRecord::Base
  attr_accessible :uploaded, :image
  after_save :save_image

  def image_data
    Base64.decode $redis.get(redis_key)
  end

  def image=(value)
    @image = value
  end

  private

  def redis_key
    @redis_key ||= "image_handle:#{id}:image"
  end

  def save_image
    $redis.set redis_key, Base64.encode(@image.read)
  end
end
于 2013-03-08T18:19:21.817 回答
0

您可以将字符串转换为 ASCII-8BIT 而不会丢失数据。更新此方法:

def image_data
  $redis.get(redis_key).force_encoding(Encoding::ASCII_8BIT)
end

它比 Base64 更快更简单。

于 2013-10-11T16:25:30.743 回答