次のコードがあります
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++;
}