将透明 PNG 转换为 JPG 时覆盖透明度颜色
我正在使用 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 倍,而且该网站的带宽已经相当大了。
I'm using Dragonfly to generate thumbnail images in a Rails app.
I'm serving all picture images as JPG's. Now the client is uploading transparent PNG files, like this one:
http://www.ibanez.co.jp/products/images/eg2010/ART120_TRF_12_02.png
Dragonfly uses RMagick to convert these images to JPG. The problem is that it converts the PNG images to JPG with a black background, and my site's design requires a white background. I've tried to override it like this:
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
But the produced JPG images still contain a black background. Does anyone know how to beat RMagick into using a white background when converting the transparent layer?
I know I could just serve as PNG, but then the images are 10 times as large, and the site is already pretty bandwidth heavy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个 ImageList,以便能够将与原始图像大小相同的白色图像放在透明图片下。如果将 ImageList 展平为图像,您将得到一个图像,其中透明颜色被第二个图像包含的任何内容替换。
我想这对我有用,但可以进一步优化。
希望有帮助!
亨德里克
You can create an ImageList to be able to put a white image with the same size as your original image UNDER the transparent picture. If you flatten the ImageList down to an image, you get an image with the transparent color replaced by whatever the second image contained.
This works for me but could be optimized further, i guess.
Hope that helps!
Hendrik
如果其他人也有同样的问题,我无法弄清楚如何通过 RMagick 做到这一点。我现在使用命令行 ImageMagick (转换)编写了一个解决方案:
If anyone else has the same problem, I wasn't able to figure out how to do this through RMagick. I've now written a solution using command line ImageMagick (convert):