在Cocoa中:如何打开图像,调整大小并使用新名称保存

时间:2013-10-28 16:41:03

标签: cocoa image-resizing nsimage

我正在尝试使用打开的对话框打开图像,调整大小并使用新名称保存它,我在其他帖子中找到了一些代码并将2或3个内容放到了我完成此代码后,但它不起作用......这是我的代码:

  -(IBAction)apriFileImmagine:(id)sender
{   
[pannelloHome makeKeyAndOrderFront:self];

int i; // Loop counter.

// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths objectAtIndex:0];
NSURL *myUrl = [NSURL fileURLWithPath:documentsDirectory2];
[openDlg setDirectoryURL:myUrl];

// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];

// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:YES];



// Display the dialog.  If the OK button was pressed,
// process the files.
if ( [openDlg runModal] == NSOKButton )
{
    // Get an array containing the full filenames of all
    // files and directories selected.
    NSArray* files = [openDlg URLs];

    // Loop through all the files and process them.
    for( i = 0; i < [files count]; i++ )
    {
        NSURL* fileName = [files objectAtIndex:i];

         [self scaleIcons:documentsDirectory2 :fileName];

    }
 }
}


- (void)scaleIcons:(NSString *)outputPath :(NSURL *)nomeImmagine
 {

 NSImage *image = [NSImage imageNamed:[NSString stringWithFormat:@"%@",nomeImmagine]];

NSSize outputSize = NSMakeSize(512.0f,512.0f);
NSImage *anImage  = [self scaleImage:image toSize:outputSize];

NSString *finalPath = [outputPath stringByAppendingString:@"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}



- (NSImage *)scaleImage:(NSImage *)image toSize:(NSSize)targetSize
{
if ([image isValid])
{
    NSSize imageSize = [image size];
    float width  = imageSize.width;
    float height = imageSize.height;
    float targetWidth  = targetSize.width;
    float targetHeight = targetSize.height;
    float scaleFactor  = 0.0;
    float scaledWidth  = targetWidth;
    float scaledHeight = targetHeight;

    NSPoint thumbnailPoint = NSZeroPoint;

    if (!NSEqualSizes(imageSize, targetSize))
    {
        float widthFactor  = targetWidth / width;
        float heightFactor = targetHeight / height;

        if (widthFactor < heightFactor)
        {
            scaleFactor = widthFactor;
        }
        else
        {
            scaleFactor = heightFactor;
        }

        scaledWidth  = width  * scaleFactor;
        scaledHeight = height * scaleFactor;

        if (widthFactor < heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }

        else if (widthFactor > heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }

        newImage = [[NSImage alloc] initWithSize:targetSize];

        [newImage lockFocus];

        NSRect thumbnailRect;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width = scaledWidth;
        thumbnailRect.size.height = scaledHeight;

        [image drawInRect:thumbnailRect
                 fromRect:NSZeroRect
                operation:NSCompositeSourceOver
                 fraction:1.0];

        [newImage unlockFocus];
    }


 }

return newImage;
}

你可以看到我正在尝试保存在拍摄图像的同一目录中...但我得到的只是一个错误:

  

:ImageIO:CGImageSourceCreateWithData数据参数为nil

任何人都知道我做错了什么?任何帮助将非常感谢...感谢Massy

2 个答案:

答案 0 :(得分:2)

仅限图片问题,图片为零,所以我修改了这个方法:

    - (void)scaleIcons:(NSString *)outputPath :(NSURL *)nomeImmagine
     {

     //NSImage *image = [NSImage imageNamed:[NSString stringWithFormat:@"%@",nomeImmagine]]; commented this part
//start modification
    NSImage     *image = [[NSImage alloc] initWithContentsOfFile:[[nomeImmagine path] autorelease]];
    if (!image)
        image = [[NSWorkspace sharedWorkspace] iconForFile:[nomeImmagine path]];
//end modification

    NSSize outputSize = NSMakeSize(512.0f,512.0f);
    NSImage *anImage  = [self scaleImage:image toSize:outputSize];

    NSString *finalPath = [outputPath stringByAppendingString:@"/icon_512x512.png"];
    NSData *imageData = [anImage TIFFRepresentation];
    NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
    NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
    [dataToWrite writeToFile:finalPath atomically:NO];
    }

试试这个,它对我有用..

答案 1 :(得分:1)

是的,这是错的。试试:

NSImage *image = [[NSImage alloc] initWithContentsOfFile:nomeImage];
NSAssert(image, @"Image is NOT valid");

这应该返回一个有效的NSImage ....?根据您是否正在使用ARC,您可能需要释放/自动释放,因为您已经“分配了”。