15

I'm using UIImageWriteToSavedPhotosAlbum to save a UIImage to the user's photo album. The problem is that the image doesn't have transparency and is a JPG. I've got the pixel data set correctly to have transparency, but there doesn't seem to be a way to save in a transparency-supported format. Ideas?

EDIT: There is no way to accomplish this, however there are other ways to deliver PNG images to the user. One of which is to save the image in the Documents directory (as detailed below). Once you've done that, you can email it, save it in a database, etc. You just can't get it into the photo album (for now) unless it is a lossy non-transparent JPG.

4

5 に答える 5

43

このSOの質問で指摘されているように、フォトアルバムにpngを保存する簡単な方法があります。

UIImage* image = ...;                                     // produce your image
NSData* imageData =  UIImagePNGRepresentation(image);     // get png representation
UIImage* pngImage = [UIImage imageWithData:imageData];    // rewrap
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);  // save to photo album
于 2012-04-23T10:46:15.323 に答える
15

これは以前から気になっていた問題で、約 1 年前にApple Developer Forumsで報告されました。私の知る限り、それはまだ未解決の問題です。

お時間がありましたら、Apple Bug Reportで機能リクエストを提出してください。より多くの人がこの問題を報告した場合、Apple がこの方法を修正して、損失のないアルファ対応の PNG を出力する可能性が高くなります。

編集

メモリ内で画像を作成できる場合は、次のようなものが機能するか、少なくとも開始できると思います。

- (UIImage *) composeImageWithWidth:(NSInteger)_width andHeight:(NSInteger)_height {
    CGSize _size = CGSizeMake(_width, _height);
    UIGraphicsBeginImageContext(_size);

    // Draw image with Quartz 2D routines over here...

    UIImage *_compositeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return _compositeImage;
}

//
// cf. https://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW20
//

- (BOOL) writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return ([data writeToFile:appFile atomically:YES]);
}

// ...

NSString *_imageName = @"myImageName.png";
NSData *_imageData = [NSData dataWithData:UIImagePNGRepresentation([self composeImageWithWidth:100 andHeight:100)];

if (![self writeApplicationData:_imageData toFile:_imageName]) {
    NSLog(@"Save failed!");
}
于 2009-09-28T21:36:00.110 に答える