Как я могу сохранить изображение из IKImageView? - PullRequest
3 голосов
/ 16 февраля 2012

Хорошо ... Я хочу сохранить видимый прямоугольник только изображения IKImageView.Моя проблема в том, что, если у меня было изображение в портретном режиме, оно не будет сохранено в правильной ориентации.Я рисую изображение с этим кодом:

[sourceImg drawInRect:targetRect fromRect:sourceRect operation:NSCompositeSourceOver fraction:1.0f];

С другой стороны, если я рисую изображение с этим кодом:

[sourceImg drawAtPoint:NSZeroPoint fromRect:sourceRect operation:NSCompositeSourceOver fraction:1.0f];

Оно будет в правильной ориентации, но редактируется какмасштабирование потеряно.Я имею в виду, что это сохранит правильный вырез, но, к сожалению, не в нужном размере.

Вот код, как я загружаю изображение:

    - (IBAction)imageSelectionButtonAction:(id)sender {
    NSLog(@"%s", __FUNCTION__);
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    id model = [self getModel];

    if (imageView) {
        [panel setAllowedFileTypes:[NSImage imageFileTypes]];
        [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] completionHandler:^(NSInteger returnCode) {
            if (returnCode == 1) {
                NSURL *imageUrl = [panel URL];
                CGImageRef          image = NULL;
                CGImageSourceRef    isr = CGImageSourceCreateWithURL( (__bridge CFURLRef)imageUrl, NULL);

                if (isr) {
                    NSDictionary *options = [NSDictionary dictionaryWithObject: (id)kCFBooleanTrue  forKey: (id) kCGImageSourceShouldCache];
                    image = CGImageSourceCreateImageAtIndex(isr, 0, (__bridge CFDictionaryRef)options);

                    if (image) {
                        _imageProperties = (__bridge_transfer NSDictionary*)CGImageSourceCopyPropertiesAtIndex(isr, 0, (__bridge CFDictionaryRef)_imageProperties);
                        _imageUTType = (__bridge NSString*)CGImageSourceGetType(isr);
                    }
                    CFRelease(isr);
                }

                if (image) {
                    [imageView setImage:image imageProperties:_imageProperties];
                    CGImageRelease(image);
                }
                [[model saveTempMutabDict] setValue:[imageUrl absoluteString] forKey:@"tempImage"];
            }   
        }];
        return;
    }
}

А вот код, каксохрани это:

    - (void)saveImage:(NSString *)path  {
    // get the current image from the image view

    CGImageRef sourceImgRef = [imageView image];
    NSRect targetRect = [imageView visibleRect];
    NSImage *sourceImg = [[NSImage alloc] initWithCGImage:sourceImgRef size:NSZeroSize];

    NSMutableDictionary *thisTiffDict = [_imageProperties valueForKey:@"{TIFF}"];
    NSInteger theOrientation = [[thisTiffDict valueForKey:@"Orientation"] integerValue];
    NSImage *targetImg = nil;
    if (theOrientation == 6) {
        targetImg = [[NSImage alloc] initWithSize:NSMakeSize([imageView frame].size.height, [imageView frame].size.width)];
    } else {
        targetImg = [[NSImage alloc] initWithSize:NSMakeSize([imageView frame].size.width, [imageView frame].size.height)];
    }

    NSRect sourceRect = [imageView convertViewRectToImageRect:targetRect];

    [targetImg lockFocus];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
    [sourceImg drawAtPoint:NSZeroPoint fromRect:sourceRect operation:NSCompositeSourceOver fraction:1.0f];
    [targetImg unlockFocus];

    _saveOptions = [[IKSaveOptions alloc] initWithImageProperties:_imageProperties imageUTType: _imageUTType];
    NSString * newUTType = [_saveOptions imageUTType];

    CGImageRef targetImgRef = [targetImg CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil];

    if (targetImgRef) {
        NSURL *url = [NSURL fileURLWithPath: path];
        CGImageDestinationRef dest = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, (__bridge CFStringRef)newUTType, 1, NULL);

        if (dest) {
            CGImageDestinationAddImage(dest, targetImgRef, (__bridge CFDictionaryRef)[_saveOptions imageProperties]);
            CGImageDestinationFinalize(dest);
            CFRelease(dest);
        }
    }
}

Понятия не имею, что я делаю не так?

Спасибо, Дженс

...