title: Iphone Converting IplImage to UIImage and back causes rotation
body: <p>I am using some code to convert between iplimage and uiimage. I take a photo taken from the camera (a UIImage) and convert it to an iplimage and back using the code posted below. Unfortunately this causes the image to be rotated and stretched by 90 degrees. 
  so if I take a 320x480 image it comes back a 320x480 image but the image has been rotated and rescaled so that it looks as if it were rotated 90 degrees (i.e a a 480x320 image) then scaled non-uniformly ... I cannot figure it out -- everything seems right (byte ordering etc.)</p>
  
  <pre><code>+(IplImage *)CreateIplImageFromUIImage:(UIImage *)image {
  CGImageRef imageRef = image.CGImage;
  
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
  CGContextRef contextRef = CGBitmapContextCreate(iplimage-&gt;imageData, iplimage-&gt;width, iplimage-&gt;height,
                                                  iplimage-&gt;depth, iplimage-&gt;widthStep,
                                                  colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
  CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
  CGContextRelease(contextRef);
  CGColorSpaceRelease(colorSpace);
  
  return iplimage;
  }
  
  +(UIImage *)UIImageFromIplImage:(IplImage *)image {
  NSLog(@"IplImage (%d, %d) %d bits by %d channels, %d bytes/row %s", image-&gt;width, image-&gt;height, image-&gt;depth, image-&gt;nChannels, image-&gt;widthStep, image-&gt;channelSeq);
  
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  NSData *data = [NSData dataWithBytes:image-&gt;imageData length:image-&gt;imageSize];
  CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
  CGImageRef imageRef = CGImageCreate(image-&gt;width, image-&gt;height,
                                      image-&gt;depth, image-&gt;depth * image-&gt;nChannels, image-&gt;widthStep,
                                      colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault,
                                      provider, NULL, false, kCGRenderingIntentDefault);
  UIImage *ret = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationRight];
  CGImageRelease(imageRef);
  CGDataProviderRelease(provider);
  CGColorSpaceRelease(colorSpace);
  return ret;
  }
  </code></pre>