Search code examples
ruby-on-railsrubyimage-processingrmagick

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 default for depth and colors are 8 and 256 right?


Solution

  • 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.