2007/02/18

画像縮小

目標通り、今作っているアプリケーションでボタンを押すと、現在読み込まれている画像を縮小したファイルを吐き出す機能が実装できた。

縮小の操作については動作を完全に理解できていないので、あまり参考にしない方がよいと思うが、一応以下の操作でオリジナルの20%のサイズの画像を生成できる。

  NSImage* originalImage = [[imageModel objectAtIndex:i] copy];
NSBitmapImageRep* originalImageRep = [NSBitmapImageRep imageRepWithData:[originalImage TIFFRepresentation]];

// producing a scaled image
// scale to 20%
NSSize rect = NSMakeSize([originalImageRep pixelsWide], [originalImageRep pixelsHigh]);
// [originalImageRep release];

NSSize thumbRect;
thumbRect.width = rect.width * 0.2;
thumbRect.height = rect.height * 0.2;

NSImage* image = [[[NSImage alloc] initWithSize:thumbRect] autorelease];
[image lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[originalImage setScalesWhenResized:YES];
[originalImage setSize:thumbRect];
[originalImage compositeToPoint:NSZeroPoint operation:NSCompositeCopy];
[image unlockFocus];

次に、生成した画像をJPEGファイルとして保存する手順についてメモしておく。手順としては、NSImageからNSBitmapImageRepを取得する。NSBitmapImageRepをJPEGデータとしてNSDataを生成する。これをファイルに書き出せばOKだ。

// Saving to disk
NSData* imageData = [image TIFFRepresentation];
NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithData: imageData];
NSDictionary* imageProps = [NSDictionary dictionaryWithObject: [NSNumber numberWithFloat: 0.9] forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];

NSString* outputFilename = [NSString stringWithFormat:@"/tmp/output%d.jpg", i];
[imageData writeToFile:outputFilename atomically:NO];

0 件のコメント: