PascalMagick – MagickDistortImage in Delphi

Playing around with ImageMagick I found that somebody already wrote a Pascal/Delphi import unit for it called PascalMagick. Unfortunately it has been integrated into freepascal which means Delphi support no longer has any priority.

So, the first thing to do was getting it to compile with Delphi.
It requires the ctypes unit from freepascal which did not compile because of an {$if …} that was terminated with an ${endif} rather than ${ifend} (line 107, newer versions fo Delphi won’t complain about this any more).

Then I opened one of the examples. There is a DPR file with an associated DPROJ file, but unfortunately that file was not a Delphi project file but some XML stuff. I renamed the LPR file (Lazarus Project) to DPR and it loaded into Delphi 2007.

Compiling worked too, but when I started it, I immediately got a System Exception with some cryptic error message. Half an hour later I knew the cause: The DLL could not be loaded, because there is an {$IFDEF Windows} around the MagickExport and WandExport constants (ImagageMagick.pas line 45). Delphi does not by default define this symbol. So I added it and the DLL still could not be found. WTF? Turned out that the DLL name was wrong. It’s now CORE_RL_MagickWand_.dll rather than CORE_RL_Wand_.dll. After that change the example program actually worked.

But I did not want to do the simple stuff but was interested in writing code that does what ‘magick -distort Perspective’ does. And I could not find anything in those units and include files that looked promising. Google finally turned up the MagickDistortImage function which is simply missing from import unit. So I added it:

  TMagickDistortImage = function(wand: PMagickWand; Method: DistortMethod; NumOfArgs: Integer;
        arguments: PDouble; bestfit: MagickBooleanType): MagickBooleanType; cdecl;

    MagickDistortImage: TMagickDistortImage;

  MagickDistortImage := GetProcAddress('MagickDistortImage');

But which values can be passed to the Method parameter? Again, it took me a while to find that enum declaration in C, so I converted it to Delphi:

  DistortMethod = (
    AffineDistortion, AffineProjectionDistortion, ScaleRotateTranslateDistortion,
    PerspectiveDistortion, PerspectiveProjectionDistortion,
    BilinearDistortion = BilinearForwardDistortion,
    BilinearReverseDistortion, PolynomialDistortion, ArcDistortion, PolarDistortion,
    DePolarDistortion, Cylinder2PlaneDistortion, Plane2CylinderDistortion, BarrelDistortion,
    BarrelInverseDistortion, ShepardsDistortion, ResizeDistortion, SentinelDistortion);

That’s how far I have come by now. I’ll put this here in case somebody else is as desparately looking for these declarations as I was for the last few hours.