我有以下代码
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
// handle error
}
else if (! [isValidDirectory boolValue]) {
// No error and it’s not a directory; do something with the file
NSString* outP = [url absoluteString];
NSString* extension = [outP substringFromIndex: outP.length-3];
NSString* img = @"png";
if([extension isEqualToString:img]){
NSImage *original = [[NSImage alloc] initWithContentsOfURL: url];
NSSize sizes = NSMakeSize(240, 240);
NSImage *small =original;
[small setSize:sizes];
NSArray* representations = [small representations];
NSInteger* total = [substrings count];
NSData* bitmapData = [NSBitmapImageRep representationOfImageRepsInArray: representations usingType: NSPNGFileType properties:nil];
[bitmapData writeToFile:@"/Users/testuser/downloads/test/test_tn.png" atomically:NO];
}
当我运行它时,它不会调整图像的大小,它只是给我一个名为 test_tn.png 的图像的直接副本,而不是一个较小的图像。我不确定我做错了什么,这也是一个mac应用程序。里面有一些未使用的代码供以后使用。问题是我在调整大小后如何将 NSImage 传递给 NSData 吗?
编辑:好的,所以我将 NSData 转换回 NSImage ,看起来 NSData 没有获得大小数据,而是原始数据。
编辑2:所以这有效
好的,所以这行得通
if([extension isEqualToString:img]){
NSImage *image = [[NSImage alloc] initWithContentsOfURL: url];
NSData *sourcedata =[image TIFFRepresentation];
NSSize newSize;
newSize.height = 160;
newSize.width = 120;
NSImage *sourceImage =[[NSImage alloc] initWithData: sourcedata];
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(240, 240)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, 240, 240) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSData *resizedPreviewData = [resizedImage TIFFRepresentation];
NSBitmapImageRep *resizedCaptureImageBitmapRep = [[NSBitmapImageRep alloc] initWithData:resizedPreviewData];
NSData* saveData = [resizedCaptureImageBitmapRep representationUsingType:NSPNGFileType properties:nil];
[saveData writeToFile:@"/Users/testuser/downloads/test/test_tn.png" atomically:YES];
count++;
}