6

I am making a simple program that creates game cards for a game I play. I have sent it out to some friends of mine for testing, but they really want it to save images, not just print them. I have tried to make it save as a .png file. I have to questions here.

  • How can I make it save my view as a .png file, including all of the view's NSImageWells.

  • How can I add an NSPopupButton to an NSSavePanel to allow users to select a format?

Any help is greatly appreciated.

Justin
  • 2,122
  • 3
  • 27
  • 47

2 Answers2

12

First create a TIFF representation of your view:

// Get the data into a bitmap.
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self bounds]];
[self unlockFocus];
data = [rep TIFFRepresentation];

To support multiple file types, use:

data = [rep representationUsingType:(NSBitmapImageFileType)storageType
properties:(NSDictionary *)properties];

NSBitmapImageFileType is an enum constant specifying a file type for bitmap images. It can be NSBMPFileType, NSGIFFileType, NSJPEGFileType, NSPNGFileType, or NSTIFFFileType.

If you need to customize the NSSavePanel, look into accessory views: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/AppFileMgmt/Articles/ManagingAccessoryViews.html

Stephen Poletto
  • 3,645
  • 24
  • 24
  • Edit: whoops, re-read it. Didn't realize you've already covered that. Will remove it in a few. – Tejaswi Yerukalapudi Mar 30 '11 at 20:40
  • 2
    -[NSData writeToFile:(NSString *)path atomically:(BOOL)flag] will be of interest. – Stephen Poletto Mar 30 '11 at 20:41
  • Ok. I got it to work by adding this code:[data writeToFile:[savePanel filename] atomically:YES];. The idea came from this [this](http://blog.objectgraph.com/index.php/2010/04/05/download-an-image-and-save-it-as-png-or-jpeg-in-iphone-sdk/) website. – Justin Mar 30 '11 at 20:45
4
// Get the data into a bitmap.
[viewBarChart lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[viewBarChart bounds]];
[viewBarChart unlockFocus];
NSData *exportedData = [rep representationUsingType:NSJPEGFileType properties:nil];

NSSavePanel *savepanel = [NSSavePanel savePanel];
savepanel.title = @"Save chart";

[savepanel setAllowedFileTypes:[NSArray arrayWithObject:@"jpg"]];

[savepanel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result)
 {
     if (NSFileHandlingPanelOKButton == result)
     {
         NSURL* fileURL = [savepanel URL];

         if ([fileURL.pathExtension isEqualToString:@""])
             fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];

         [exportedData writeToURL:fileURL atomically:YES];
     }

     [rep release];
 }];
Catalin
  • 1,821
  • 4
  • 26
  • 32