title: Saving an image in a NSView
body: <p>I have problem with <code>rotating</code> and saving <code>JPEG</code> <code>NSImage</code>. I have <code>NSView</code> which is flipped</p>
  
  <pre><code>- (BOOL)isFlipped
  {
    return YES;
  }
  </code></pre>
  
  <p>Then I'm applying <code>NSImage</code> rotation with following function:</p>
  
  <pre><code>- (NSImage*)imageRotatedByDegrees:(CGFloat)degrees
  {
    // calculate the bounds for the rotated image
    NSRect imageBounds = {NSZeroPoint, [image size]};
    NSBezierPath* boundsPath = [NSBezierPath
                            bezierPathWithRect:imageBounds];
    NSAffineTransform* transform = [NSAffineTransform transform];
  
    [transform rotateByDegrees:degrees];
    [boundsPath transformUsingAffineTransform:transform];
  
    NSRect rotatedBounds = {NSZeroPoint, [boundsPath bounds].size};
    NSImage* rotatedImage = [[NSImage alloc]
                          initWithSize:rotatedBounds.size];
  
    // center the image within the rotated bounds
    imageBounds.origin.x = NSMidX(rotatedBounds) - (NSWidth
                                                (imageBounds) / 2);
    imageBounds.origin.y = NSMidY(rotatedBounds) - (NSHeight
                                                (imageBounds) / 2);
  
    // set up the rotation transform
    transform = [NSAffineTransform transform];
    [transform translateXBy:+(NSWidth(rotatedBounds) / 2) yBy:+
     (NSHeight(rotatedBounds) / 2)];
    [transform rotateByDegrees:degrees];
    [transform translateXBy:-(NSWidth(rotatedBounds) / 2) yBy:-
     (NSHeight(rotatedBounds) / 2)];
  
    // draw the original image, rotated, into the new image
    [rotatedImage lockFocus];
    [transform set];
    [image drawInRect:imageBounds fromRect:NSZeroRect
       operation:NSCompositeCopy fraction:1.0] ;
    [rotatedImage unlockFocus];
  
    return  rotatedImage;
  }
  </code></pre>
  
  <p>Image is now successfully rotated. Later, when I'm trying to save JPEG with following code:</p>
  
  <pre><code>-(void)saveDocument:(id)sender
  {
    NSData *imageData = [image TIFFRepresentation];
    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
    NSDictionary *imageProps = 
      [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] 
                    forKey:NSImageCompressionFactor];
    imageData = [imageRep representationUsingType:NSJPEGFileType 
                                       properties:imageProps];
    [imageData writeToFile:[_imageURL path] atomically:YES];
  }
  </code></pre>
  
  <p>Result <code>JPEG</code> file is incorrectly flipped... What I'm doing wrong ?</p>
  
  <p>Thanks a lot for any ideas, Petr</p>