开发者

RMagick weird green gif when setting image_type

So I got this following code trying to convert a png to gif in ruby using RMagick, but got some weird green stuff on some part of the image.

require 'RMagick'
include Magick
img = Magick::Image.read(pngPath.open).first
//if comment out the following line, there is no problem
img.image_type=PaletteMatteType
img.transparent("#00FF00")
img.write(gifPath)

PS: how to change the depth to 8 or 16 and How to change colors to 256? The d开发者_如何转开发efault for depth and colors are 8 and 256 right?


Most RMagick methods return the new image rather than modifying it in-place; some methods have ! versions for modifying things in place (such as scale and scale!) but some don't (such as quantize).

In particular, transparent returns the new image:

img.transparent(color, opacity=TransparentOpacity) -> image
[...]
Returns
A new image

So just saying img.transparent("#00FF00") creates a new image with the desired transparency and then throws it away because you are ignoring the return value.

Also, the usual way to drop something down to a smaller palette is to use quantize.

I think you want something like this:

img = Magick::Image.read(pngPath.open).first
img = img.transparent('#00FF00')
img = img.quantize(256)
img.write(gifPath)

Works for me at least.


Not sure about the defaults by I would change a couple of thing:

if you require RMagick, there is no need to include Magick afterwards, I think you can delete this line.

Constants should be prefixed by Magick::, so it should probably be Magick::PaletteMatteType

the transparent method takes 2 arguments, the first one being the color that you want to make transparent, and the second is the kind of transparency. I think Gif knows only one kind, but anyway, try

img.transparent("#00FF00", Magick::TransparentOpacity)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜