将透明PNG转换为JPG时覆盖透明度颜色

时间:2010-05-31 08:06:53

标签: ruby rmagick dragonfly-gem

我正在使用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倍,并且网站的带宽非常大。

2 个答案:

答案 0 :(得分: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

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

希望有所帮助! 亨德里克

答案 1 :(得分:0)

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

  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