0

I am trying to convert the following ImageMagick command into objective-c:

convert photo.png -posterize 6 photo2.png

I'm basically just trying to take some UIImage and apply the simple posterize effect to it. I written up the code below and it's not having any effect on the image. It is not throwing any exceptions or failing. I have a failling I'm either screwing up with the command arguments or the image input / output. Does anyone have any suggestions on how to fix this?

MagickWandGenesis();
MagickWand *wand = NewMagickWand();
NSData *data = UIImagePNGRepresentation(self.originalImage);
MagickReadImageBlob(wand, [data bytes], [data length]);

int arg_count = 2;
char *args[] = { "-posterize", "6", NULL};

ImageInfo *image_info = AcquireImageInfo();
ExceptionInfo *exception = AcquireExceptionInfo();

MagickBooleanType status = ConvertImageCommand(image_info, arg_count, args, NULL, exception);

if (exception->severity != UndefinedException)
{
    status = MagickTrue;
    CatchException(exception);
}

if (status == MagickFalse)
{
    NSLog(@"FAIL");
}

self.imageView.image = self.originalImage;

image_info=DestroyImageInfo(image_info);
exception=DestroyExceptionInfo(exception);
DestroyMagickWand(wand);
MagickWandTerminus();
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ser Pounce
  • 14,196
  • 18
  • 84
  • 169

1 Answers1

1

I believe your looking for Imagemagick's MagickPosterizeImage.

MagickWandGenesis();
MagickWand *wand = NewMagickWand();
NSData *data = UIImagePNGRepresentation(self.originalImage);
MagickReadImageBlob(wand, [data bytes], [data length]);

MagickBooleanType = status;

status = MagickPosterizeImage(wand,6,MagickFalse);
if (status == MagickFalse)
{
    NSLog(@"FAIL");
}

// Convert wand back to UIImage
unsigned char * c_blob;
size_t data_length;
c_blob = MagickGetImageBlob(wand,&data_length);
data = [NSData dataWithBytes:c_blob length:data_length];
self.imageView.image = [UIImage imageWithData:data];

DestroyMagickWand(wand);
MagickWandTerminus();

MagickPosterizeImage

There's also MagickOrderedPosterizeImage & MagickOrderedPosterizeImageChannel to fine-tune dithering thresholds, and target color channels.

MagickOrderedPosterizeImageChannel

emcconville
  • 23,800
  • 4
  • 50
  • 66
  • Thank you that worked perfectly. Do you happen to know why ConvertImageCommand might not have worked? I still need to use this function for some other commands that I need to convert that I don't believe have direct API calls like posterize. – Ser Pounce Apr 17 '14 at 17:30
  • 1
    You need to add `MagickCommandGenesis` to use `ConvertImageCommand`. But for the argument of performance & complexity, just use the MagickWand/Core methods directly. It's just easier. – emcconville Apr 17 '14 at 18:12
  • I also have issues getting the ConvertImageCommand to work, and I need it to convert between file formats – SwiftMatt Mar 27 '16 at 20:06