Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Rotate a UIImage 90 degrees?
    text
    copied!<p>I have a <code>UIImage</code> that is <code>UIImageOrientationUp</code> (portrait) that I would like to rotate counter-clockwise by 90 degrees (to landscape). I don't want to use a <code>CGAffineTransform</code>. I want the pixels of the <code>UIImage</code> to actually shift position. I am using a block of code (shown below) originally intended to resize a <code>UIImage</code> to do this. I set a target size as the current size of the <code>UIImage</code> but I get an error:</p> <blockquote> <p>(Error): CGBitmapContextCreate: invalid data bytes/row: should be at least 1708 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedLast.</p> </blockquote> <p>(I don't get an error whenever I provide a SMALLER size as the target size BTW). How can I ROTATE my <code>UIImage</code> 90 degrees CCW using just core graphics functions while preserving the current size?</p> <pre><code>-(UIImage*)reverseImageByScalingToSize:(CGSize)targetSize:(UIImage*)anImage { UIImage* sourceImage = anImage; CGFloat targetWidth = targetSize.height; CGFloat targetHeight = targetSize.width; CGImageRef imageRef = [sourceImage CGImage]; CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); if (bitmapInfo == kCGImageAlphaNone) { bitmapInfo = kCGImageAlphaNoneSkipLast; } CGContextRef bitmap; if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) { bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } else { bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } if (sourceImage.imageOrientation == UIImageOrientationRight) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } else if (sourceImage.imageOrientation == UIImageOrientationLeft) { CGContextRotateCTM (bitmap, radians(-90)); CGContextTranslateCTM (bitmap, -targetWidth, 0); } else if (sourceImage.imageOrientation == UIImageOrientationDown) { // NOTHING } else if (sourceImage.imageOrientation == UIImageOrientationUp) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef); CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* newImage = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); CGImageRelease(ref); return newImage; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload