在 Mac OS X App Cocoa 中生成图像文件时出现问题


-(void)processImage:(NSString*)inputPath:(int)imageWidth:(int)imageHeight:(NSString*)outputPath {
 //   NSImage * img = [NSImage imageNamed:inputPath];
    NSImage *image = [[NSImage alloc] initWithContentsOfFile:inputPath];
    [image setSize: NSMakeSize(imageWidth,imageHeight)];
    [[image TIFFRepresentation] writeToFile:outputPath atomically:NO];
    NSLog(@"image file created");
}
- (IBAction)processImage:(id)sender {
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    // NSTimeInterval is defined as double
    NSNumber *timeStampObj = [NSNumber numberWithInt:timeStamp];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterNoStyle];
    NSString *convertNumber = [formatter stringForObjectValue:timeStampObj];
    NSLog(@"timeStampObj:: %@", convertNumber);
    fileNameNumber = [[convertNumber stringByAppendingString:[self genRandStringLength:8]] retain];
    int i; // Loop counter.
    // Loop through all the files and process them.
    for( i = 0; i < [files count]; i++ )
    {
        inputFilePath = [[files objectAtIndex:i] retain];
        NSLog(@"filename::: %@", inputFilePath);
        // Do something with the filename.
        [selectedFile setStringValue:inputFilePath];
        NSLog(@"selectedFile:::: %@", selectedFile);
    }
    NSLog(@"curdir:::::%@", inputFilePath);
    NSString *aString = [[NSString stringWithFormat:@"%@%@%@", thumbnailDirPath , @"/" , fileNameNumber] retain];
    fileNameJPG = [[aString stringByAppendingString:@"_small.jpg"] retain];
    fileNameJPG1 = [[aString stringByAppendingString:@".jpg"] retain];
    fileNameJPG2 = [[aString stringByAppendingString:@"_H.jpg"] retain];
        [self processImage:inputFilePath: 66  :55  :fileNameJPG];
        [self processImage:inputFilePath: 800 :600 :fileNameJPG1];
        [self processImage:inputFilePath: 320 :240 :fileNameJPG2];
}

面临的问题是,上面的代码正在生成 3 个具有不同名称的文件(正如我定义的名称应该是(,它们与所有 3 个文件的大小相同,但尺寸或宽度/长度与我传递给函数不同。

可能是什么问题?

NSImage对象是不可变的。因此,当您更改其大小时image不会被修改。

您应该使用类似于以下代码的内容(改编自此处(。

-(void)saveImageAtPath:(NSString*)sourcePath toPath:(NSString*)targetPath withWidth:(int)targetWidth andHeight:(int)targetHeight
{
    NSImage *sourceImage = [[NSImage alloc] initWithContentsOfFile:sourcePath];
    NSImage *targetImage = [[NSImage alloc] initWithSize: NSMakeSize(targetWidth, targetHeight)];
    NSSize sourceSize = [sourceImage size];
    NSRect sourceRect = NSMakeRect(0, 0, sourceSize.width, sourceSize.height);
    NSRect targetRect = NSMakeRect(0, 0, targetWidth, targetWidth);
    [targetImage lockFocus];
    [sourceImage drawInRect:targetRect fromRect:sourceRect  operation: NSCompositeSourceOver fraction: 1.0];
    [targetImage unlockFocus];
    [[targetImage TIFFRepresentation] writeToFile:targetPath atomically:NO];
    NSLog(@"image file created");
    [sourceImage release];
    [targetImage release];
}

最新更新