我在用着 蜻蜓 在Rails应用程序中生成缩略图图像。

我将所有图像作为JPG的图像。现在,客户正在上传透明的png文件,例如:

http://www.ibane.co.jp/products/images/eg2010/art120_trf_12_02.png

蜻蜓使用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倍,并且该站点已经很重。

有帮助吗?

解决方案

您可以创建一个图像学家,以便能够在透明图片下放置与原始图像相同的白色图像。如果将成像板弄平到图像,则会获得图像,其透明颜色被第二张图像所取代。

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

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

希望有帮助!亨德里克

其他提示

如果其他人有同样的问题,我将无法通过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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top