Search code examples
iosobjective-cimageuiimagecifilter

White pixels around iOS Image using CIFilter


I add a picture frame (Image with transparent background) around an existing UIImage and save it all as one image. On simulator, everything looks like it runs great. However on the device, it adds some white pixels around some of the areas of the frame's image. Here is my code:

- (void)applyFilter {
    NSLog(@"Running");

    UIImage *borderImage = [UIImage imageNamed:@"IMG_8055.PNG"];

    NSData *dataFromImage = UIImageJPEGRepresentation(self.imgView.image, 1);

    CIImage *beginImage= [CIImage imageWithData:dataFromImage];

    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *border =[CIImage imageWithData:UIImagePNGRepresentation(borderImage)];
    border = [border imageByApplyingTransform:CGAffineTransformMakeScale(beginImage.extent.size.width/border.extent.size.width, beginImage.extent.size.height/border.extent.size.height)];

    CIFilter *filter= [CIFilter filterWithName:@"CISourceOverCompositing"];  //@"CISoftLightBlendMode"];
    [filter setDefaults];
    [filter setValue:border forKey:@"inputImage"];

    [filter setValue:beginImage forKey:@"inputBackgroundImage"];

    CIImage *outputImage = [filter valueForKey:@"outputImage"];







    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *newImg = [UIImage imageWithCGImage:cgimg];

    self.imgView.image = newImg;

}

Here is the resulting image:

enter image description here

The frame image used in the picture looks like this:

enter image description here

Here is a screenshot of the frame image in photoshop, showing those pixels are not present in the PNG.

enter image description here


Solution

  • The issue is that if you look at your image, those pixels immediately adjacent to the musical notes are apparently not transparent. And if you notice, those white pixels that appear in the final image aren't just the occasional pixel, but they appear in square blocks.

    These sorts of squared-off pixel noise is a telltale sign of JPEG artifacts. It's hard to say what's causing this because the image you added to this question was a JPEG (which doesn't support transparency). I assume you must have a PNG version of this backdrop? You might have to share that with us to confirm this diagnosis.

    But the bottom line is that you need to carefully examine the original image and the transparency of those pixels that appear to be white noise. Make sure that as you create/manipulate these images, avoid JPEG file formats, because it loses transparency information and introduces artifacts. PNG files are often safer.