Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you superimpose two images using MagickWand?

I was just looking at Raku's MagickWand interface to imagemagick:

https://modules.raku.org/dist/MagickWand

And I don't see any way to superimpose two images. There's an MagickWand.append-wands demonstrated in examples/01-hello.pl6 that tiles images, and I see there's a montage method in the code (for creating moving gifs?), but I don't see anything like the Flatten method I've used with perl's Image::Magick.

like image 980
Joseph Brenner Avatar asked Oct 25 '20 16:10

Joseph Brenner


Video Answer


1 Answers

I've got some code working using MagickMergeImageLayers, I subclassed MagickWand and added a method to do it (following along with what was done in the append-wands method).

Here's the subclass module:

use MagickWand;

use NativeCall;
use MagickWand::NativeCall;
use MagickWand::NativeCall::DrawingWand;
use MagickWand::NativeCall::Image;
use MagickWand::NativeCall::Mogrify;
use MagickWand::NativeCall::PixelIterator;
use MagickWand::NativeCall::PixelWand;
use MagickWand::NativeCall::Property;
use MagickWand::NativeCall::Wand;
use MagickWand::NativeCall::WandView;
use MagickWand::NativeCall::Deprecated;
use MagickWand::Enums;

class MagickWand::Doomed is MagickWand {

    submethod flatten-wands(+@wands) returns MagickWand {
        die "List must be defined with at least two elements" unless @wands.defined && @wands.elems >= 2;
        my $temp-wand = NewMagickWand;  # this "wand" is a cpointer
        MagickSetLastIterator($temp-wand);

        for @wands -> $wand {
            MagickAddImage($temp-wand, $wand.handle);  
            MagickSetLastIterator($temp-wand);
        }

        MagickSetFirstIterator($temp-wand);
        # an integer expected as second argument but the value
        # doesn't seem to do anything
        my $cloned-wand = MagickMergeImageLayers( $temp-wand, 0 );   

        DestroyMagickWand( $temp-wand );
        return MagickWand.new( handle => $cloned-wand );
    }
}

Some sample script code that uses the above:

use MagickWand::Doomed;

my @images;  # stack of images to process ("wands", i.e. MagickWand objects)

my $bg = MagickWand::Doomed.new;
$bg.read( $input_image_file );
my ($w, $h) = ($bg.width, $bg.height);
$bg.label("conan_limits");
@images.push( $bg );

my    $overlay = MagickWand::Doomed.new;
$overlay.create( $w, $h, 'transparent' );  
$overlay.draw-line( 150, 120,  190, 70 );
$overlay.draw-line( 190, 70,   220, 120 );
$overlay.draw-line( 220, 120,  150, 120 );

$overlay.label("drawn");
@images.push( $overlay );

my $output_file = "$loc/flattened-output.png";
my $comparison = MagickWand::Doomed.flatten-wands( @images );
$comparison.write( $output_file );

# cleanup on exit
LEAVE {
  for @images -> $image {
    $image.cleanup   if $image.defined;  
  }
}
like image 92
Joseph Brenner Avatar answered Oct 25 '22 08:10

Joseph Brenner