Round corners RMagick

You need an easy way to round the image. I need the corners to be transparent. This link shows how to do this through the command line:

http://www.imagemagick.org/Usage/thumbnails/#rounded

I need the appropriate RMagick \ Ruby code ... Thanks!

+3
source share
5 answers
+2
source

Include Rmagick in your source code. Be sure to place the include inside the class declaration.

require 'rmagick'
include Magick

Create a method like this

def thumb(source_image, geometry_string, radius = 10)
  source_image.change_geometry(geometry_string) do |cols, rows, img| 

    # Make a resized copy of the image
    thumb = img.resize(cols, rows)

    # Set a transparent background: pixels that are transparent will be
    # discarded from the source image.
    mask = Image.new(cols, rows) {self.background_color = 'transparent'}

    # Create a white rectangle with rounded corners. This will become the
    # mask for the area you want to retain in the original image.
    Draw.new.stroke('none').stroke_width(0).fill('white').
        roundrectangle(0, 0, cols, rows, radius, radius).
        draw(mask)

    # Apply the mask and write it out
    thumb.composite!(mask, 0, 0, Magick::CopyOpacityCompositeOp)
    thumb
  end
end

Call a method like this

source_image = Image.read('my-big-image.jpg').first
thumbnail_image = thumb(source_image, '64x64>', 8)
thumbnail_image.write('thumb.png')

, , , . , .

, , http://www.imagemagick.org/RMagick/doc/imusage.html#geometry

+9

Fitter Man CarrierWave::RMagick

:

def resize_and_round(geometry_string, radius = 10)
  manipulate! do |original|
    original.change_geometry(geometry_string) do |cols, rows, img| 

      # Make a resized copy of the image
      thumb = img.resize(cols, rows)

      # Set a transparent background: pixels that are transparent will be
      # discarded from the source image.
      mask = Magick::Image.new(cols, rows) {self.background_color = 'transparent'}

      # Create a white rectangle with rounded corners. This will become the
      # mask for the area you want to retain in the original image.
      Magick::Draw.new.stroke('none').stroke_width(0).fill('white').
          roundrectangle(0, 0, cols, rows, radius, radius).
          draw(mask)

      # Apply the mask and write it out
      thumb.composite!(mask, 4,4, Magick::CopyOpacityCompositeOp)
      thumb
    end
  end
end

:

process :resize_and_round => ['200x200', 20]
+4

, RMagick, system() , . , , .

+1

Source: https://habr.com/ru/post/1742881/


All Articles