Skip to content

Instantly share code, notes, and snippets.

@zachwaugh
Created October 5, 2011 16:50
Show Gist options
  • Save zachwaugh/1264981 to your computer and use it in GitHub Desktop.
Save zachwaugh/1264981 to your computer and use it in GitHub Desktop.
NSImage category for writing image to file
// [image writeToFile:[NSURL fileURLWithPath:@"/some/path/image.png"]];
- (void)writeToFile:(NSURL *)fileURL
{
NSBitmapImageRep *bitmapRep = nil;
for (NSImageRep *imageRep in [self representations])
{
if ([imageRep isKindOfClass:[NSBitmapImageRep class]])
{
bitmapRep = (NSBitmapImageRep *)imageRep;
break; // stop on first bitmap rep we find
}
}
if (!bitmapRep)
{
bitmapRep = [NSBitmapImageRep imageRepWithData:[self TIFFRepresentation]];
}
NSData *imageData = [bitmapRep representationUsingType:[self fileTypeForFile:[fileURL lastPathComponent]] properties:nil];
[imageData writeToURL:fileURL atomically:NO];
}
- (NSBitmapImageFileType)fileTypeForFile:(NSString *)file
{
NSString *extension = [[file pathExtension] lowercaseString];
if ([extension isEqualToString:@"png"])
{
return NSPNGFileType;
}
else if ([extension isEqualToString:@"gif"])
{
return NSGIFFileType;
}
else if ([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"])
{
return NSJPEGFileType;
}
else
{
return NSTIFFFileType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment