wandpixelaccess.pas 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. {
  2. Demonstration program for the ImageMagick Library
  3. Usage: Just execute the program. It will change all black pixels
  4. in the image.png image on it's directory to be transparent
  5. and then it will save it as image2.png
  6. The idea is to demonstrate pixel access using MagickWand.
  7. }
  8. program wandpixelaccess;
  9. {$mode objfpc}{$H+}
  10. uses SysUtils, magick_wand, ImageMagick, ctypes;
  11. procedure ThrowWandException(wand: PMagickWand);
  12. var
  13. description: PChar;
  14. severity: ExceptionType;
  15. begin
  16. description := MagickGetException(wand, @severity);
  17. WriteLn(Format('An error ocurred. Description: %s', [description]));
  18. description := MagickRelinquishMemory(description);
  19. Abort;
  20. end;
  21. var
  22. status: MagickBooleanType;
  23. wand: PMagickWand = nil;
  24. pixel: MagickPixelPacket;
  25. iterator: PPixelIterator;
  26. pixels: PPPixelWand = nil;
  27. x, y: Integer;
  28. width: culong;
  29. begin
  30. { Read an image. }
  31. MagickWandGenesis;
  32. wand := NewMagickWand();
  33. try
  34. status := MagickReadImage(wand, 'image.png');
  35. if (status = MagickFalse) then ThrowWandException(wand);
  36. iterator := NewPixelIterator(wand);
  37. if (iterator = nil) then ThrowWandException(wand);
  38. for y := 0 to MagickGetImageHeight(wand) - 1 do
  39. begin
  40. // WriteLn(' Line ', y, ' from ', MagickGetImageHeight(wand) - 1);
  41. pixels := PixelGetNextIteratorRow(iterator, width);
  42. if (pixels = nil) then Break;
  43. for x := 0 to width - 1 do
  44. begin
  45. // WriteLn(Format(' x %d y %d r %f g %f b %f o %f',
  46. // [x, y, pixel.red, pixel.green, pixel.blue, pixel.opacity]));
  47. PixelGetMagickColor(pixels[x], @pixel);
  48. if (pixel.red = 0.0) and
  49. (pixel.green = 0.0) and
  50. (pixel.blue = 0.0) then
  51. begin
  52. pixel.opacity := QuantumRange;
  53. pixel.matte := QuantumRange; // matte=alpha
  54. end;
  55. PixelSetMagickColor(pixels[x], @pixel);
  56. end;
  57. PixelSyncIterator(iterator);
  58. end;
  59. // if y < MagickGetImageHeight(wand) then ThrowWandException(wand);
  60. iterator := DestroyPixelIterator(iterator);
  61. { Write the image }
  62. status := MagickWriteImage(wand, 'image2.png');
  63. if (status = MagickFalse) then ThrowWandException(wand);
  64. finally
  65. { Clean-up }
  66. if wand <> nil then wand := DestroyMagickWand(wand);
  67. MagickWandTerminus;
  68. end;
  69. end.