4

我正在使用Dragonfly在 Rails 应用程序中生成缩略图。

我将所有图片图像作为 JPG 提供。现在客户端正在上传透明的 PNG 文件,如下所示:

http://www.ibanez.co.jp/products/images/eg2010/ART120_TRF_12_02.png

Dragonfly 使用 RMagick 将这些图像转换为 JPG。问题是它将PNG图像转换为黑色背景的JPG,而我的网站设计需要白色背景。我试图像这样覆盖它:

encoded_image = Magick::Image.from_blob(image.data).first

if encoded_image.format.downcase == format
  image # do nothing
else
  encoded_image.format = format
  encoded_image.background_color = "white"
  encoded_image.transparent_color = "white"
  encoded_image.to_blob
end

但是生成的 JPG 图像仍然包含黑色背景。有谁知道在转换透明层时如何击败 RMagick 使用白色背景?

我知道我可以只用作 PNG,但是图像是原来的 10 倍,而且该站点的带宽已经相当大了。

4

2 回答 2

10

您可以创建一个 ImageList 以便能够在透明图片下放置与原始图像相同大小的白色图像。如果您将 ImageList 展平为一个图像,您将获得一个透明颜色的图像,该图像被第二个图像包含的任何内容所取代。

img_list = Magick::ImageList.new
img_list.read("my_png_file.png")
img_list.new_image(img_list.first.columns, img_list.first.rows) { self.background_color = "white" } # Create new "layer" with white background and size of original image
image = img_list.reverse.flatten_images

这对我有用,但我想可以进一步优化。

希望有帮助!亨德里克

于 2010-09-01T16:03:36.947 回答
0

如果其他人有同样的问题,我无法通过 RMagick 弄清楚如何做到这一点。我现在使用命令行 ImageMagick (convert) 编写了一个解决方案:

  if encoded_image.format.downcase == "png"
    temp_file = Tempfile.new(image.object_id)

    encoded_image.write("png:" + temp_file.path)

    encoded_image.destroy!

    system "convert -flatten \"#{temp_file.path}\" \"jpg:#{temp_file.path}\""

    encoded_image = Magick::Image.read(temp_file.path)[0]

    temp_file.delete
  else
于 2010-06-03T11:46:09.433 回答