Why this happens
CGBitmapContextCreate: invalid data bytes/row means the supplied row stride is too small for the bitmap context’s width and pixel format. A stride is the number of bytes reserved for one row of pixels, including any padding.
When you rotate an image by 90 degrees, its output width becomes its original height. The source image’s CGImageGetBytesPerRow describes the source layout, not necessarily the new layout. Reusing that value can fail if the destination needs a wider row. For example, a 427-pixel-wide destination with four bytes per pixel needs at least 1,708 bytes per row.
There is also a distinction between rotating image data and changing orientation metadata. A UIImage can carry an orientation value that tells UIKit how to display its underlying image. Changing that value alone does not rearrange the stored pixels.
How to fix it
1. Draw into a new image with swapped dimensions
Use UIGraphicsImageRenderer to create a destination image, then rotate the drawing context before drawing the source. This follows the drawing approach in the accepted answer, but also swaps the canvas dimensions and translates the context so the rotated image remains inside the canvas.
The following function is for an input whose imageOrientation is .up, as in the original problem:
import UIKit
func rotatedCounterclockwise(_ source: UIImage) -> UIImage {
precondition(source.imageOrientation == .up)
precondition(source.size.width > 0 && source.size.height > 0)
let outputSize = CGSize(
width: source.size.height,
height: source.size.width
)
let format = UIGraphicsImageRendererFormat()
format.scale = source.scale
format.opaque = false
let renderer = UIGraphicsImageRenderer(size: outputSize, format: format)
return renderer.image { rendererContext in
let context = rendererContext.cgContext
context.translateBy(x: 0, y: source.size.width)
context.rotate(by: -.pi / 2)
source.draw(in: CGRect(origin: .zero, size: source.size))
}
}
Use it with an image you have already loaded:
if let image = UIImage(named: "photo") {
let rotatedImage = rotatedCounterclockwise(image)
imageView.image = rotatedImage
}
The renderer draws into a new image, so the rotation is reflected in the output pixels rather than being only an orientation change. Setting the renderer’s scale to source.scale preserves the input’s point-to-pixel scale. The image’s dimensions exchange places; rotating a non-square image cannot preserve both its original width and its original height without cropping or adding empty space.
Although this code does not construct a CGAffineTransform, translateBy and rotate still change the Core Graphics context’s current transformation matrix. They affect how the image is drawn into the destination; they are not a transform applied to an image view.
2. Check your bitmap stride if you need a Core Graphics context
If you must use CGBitmapContextCreate directly, calculate the destination’s row stride from the destination pixel width and the chosen bitmap format. Do not assume the source image’s stride will work after the width and height are exchanged.
For a known format with four bytes per pixel, the minimum unpadded stride is the destination width in pixels multiplied by four. Other formats can have different requirements, and a context may use padding. Alternatively, where appropriate, pass zero for bytesPerRow and let Core Graphics choose a suitable value.
When adapting the original code:
- Read the source
CGImagedimensions in pixels, not just theUIImagesize in points. - Use the source pixel height as the destination pixel width, and the source pixel width as the destination pixel height.
- Choose a supported color space, alpha layout and bits-per-component combination for the new context.
- Supply a suitable destination stride, or let Core Graphics select it.
- Check that context creation succeeds before drawing or creating the output image.
Changing only bytesPerRow fixes the allocation error, not necessarily the rotation. The drawing operation still needs a correctly positioned destination and a 90-degree rotation. If the output is clipped, verify the canvas dimensions and translation as well as the angle.
3. Use orientation metadata only when new pixels are unnecessary
If you only need UIKit to display a CGImage-backed image with a different orientation, you can create another UIImage around the same CGImage:
import UIKit
func imageWithLeftOrientation(_ source: UIImage) -> UIImage? {
guard let cgImage = source.cgImage else { return nil }
return UIImage(
cgImage: cgImage,
scale: source.scale,
orientation: .left
)
}
This is the shorter alternative from the other highly scored answer. It retains the source scale, but it does not rotate the underlying pixel data. It also replaces the orientation value rather than applying a rotation relative to any existing orientation. If a later operation reads the cgImage directly, it receives the underlying pixels without the UIImage orientation applied.
Choose the renderer approach when downstream code needs the rotation baked into a new image. Use a visibly asymmetric test image, such as one with a label near a corner, to confirm the direction you need.
How to prevent it
- Treat
UIImage.sizeas a size in points; useCGImagedimensions when allocating a pixel buffer. - Calculate a bitmap’s stride for its destination width and pixel format, not the source’s stride.
- Swap output width and height for a 90-degree rotation.
- Preserve the source scale when rendering unless you deliberately want a different pixel density.
- Test with a non-square image and a recognizable corner marker to catch clipping and direction mistakes.
FAQ
Why did a smaller target size avoid the error?
A smaller destination width may fit within the source stride supplied to CGBitmapContextCreate. That does not make the source stride correct for every destination size or pixel format.
Does changing imageOrientation rotate the pixels?
No. Creating a UIImage with a different orientation associates display orientation with the image; it does not rearrange its underlying CGImage pixels. Draw into a new image when you need the rotation baked in.
Can I use the renderer function with any image orientation?
The function above explicitly requires .up, matching the source problem. For images with other orientation values, account for their existing orientation and verify the result rather than assuming the same transformation produces the intended rotation.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.
