Created
October 5, 2011 16:50
-
-
Save zachwaugh/1264981 to your computer and use it in GitHub Desktop.
NSImage category for writing image to file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [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