Search code examples
iphonemultithreadinguiimageresizescale

Thread safe UIImage resizing?


I made this UIImage extension to get a rescaled copy:

-(UIImage*)scaleByRatio:(float) scaleRatio
{ 
    CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio);

    //The output context.   
    UIGraphicsBeginImageContext(scaledSize);
    CGContextRef context = UIGraphicsGetCurrentContext();

//Percent (101%)    
#define SCALE_OVER_A_BIT 1.01

    //Scale.
    CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT);
    [self drawAtPoint:CGPointZero];

    //End?
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

It works in the most cases, but in my recent project it outputs the original image (I save to disk right after scaling using UIImageJPEGRepresentation and imageWithData:).

I invoke the method within a background thread. Could this be the problem? How can I rewrite this to be thread safe (supposing the problem is caused by threading).


Solution

  • -(UIImage*)scaleByRatio:(float) scaleRatio
    { 
       CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio);
       CGColorSpaceRef colorSpace;
       int   bitmapBytesPerRow;
       bitmapBytesPerRow   = (size.width * 4);
    
       //The output context.   
       UIGraphicsBeginImageContext(scaledSize);
       CGContextRef context = context = CGBitmapContextCreate (NULL,
                                     scaledSize .width,
                                     scaledSize .height,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedLast);
    
     //Percent (101%)    
     #define SCALE_OVER_A_BIT 1.01
    
        //Scale.
       CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT);
    [self drawAtPoint:CGPointZero];
    
       //End?
       UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
       return scaledImage;
     }
    

    In-short you have to Create CGContextRef using CGBitmapContextCreate not using UIGraphicsGetCurrentContext(); becuase UIGraphicsGetCurrentContext(); is not thrad safe.

    Hope, this will help you...enjoy