Skip to content

Instantly share code, notes, and snippets.

@josephsieh
Last active January 26, 2024 16:12
Show Gist options
  • Save josephsieh/19b2f180b7559c3405a1292b15080477 to your computer and use it in GitHub Desktop.
Save josephsieh/19b2f180b7559c3405a1292b15080477 to your computer and use it in GitHub Desktop.
Rotate CGImage 90 degree clock wise
-(void) rotate90Degree:(CGImageRef) cgImageRef
{
int cgImageWidth = (int)CGImageGetWidth(cgImageRef);
int cgImageHeight = (int)CGImageGetHeight(cgImageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
int targetWidth = cgImageHeight;
int targetHeight = cgImageWidth;
NSUInteger bytesPerRow = bytesPerPixel * targetWidth;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(nil, targetWidth, targetHeight,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
CGContextRotateCTM (context, -M_PI_2);
CGContextTranslateCTM(context, -(int)targetHeight, 0);
CGContextDrawImage(context, CGRectMake(0, 0, cgImageWidth, cgImageHeight), cgImageRef);
}
@andymedvedev
Copy link

andymedvedev commented May 17, 2017

You forget to extract and return rotated image like this:

CGImageRef rotatedCGImage = CGBitmapContextCreateImage(context);
return rotatedCGImage;

And in this code memory leak!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment