LoginSignup
24
23

More than 5 years have passed since last update.

カメラロールから選択した画像のパスを取得する

Posted at

カメラロールから取得した画像のパスを取得する方法。
そのパスをCoreDataにNSStringで保存したりします。
UIImagePickerControllerでカメラロールから画像を選択したあと呼ばれるメソッドに、ガチャガチャと書いていきます。

AssetsLibratyを使用するので、フレームワークを追加してヘッダーファイルに

#import <AssetsLibrary/AssetsLibrary.h>

と書いておきましょう。

実装部分は以下です。
今回はheaderImageButtonというUIButtonの背景画像を変えています。
そして、プロパティであるmanagedObjectに画像のパスをつっこんでいます。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // Pathを取得
    NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    // AssetsLibratyを作成
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
        // まずassetからバッファをつくる
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        Byte *buffer = (Byte*)malloc(rep.size);
        NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; //これが必要なデータ
        // データからUIImageを作成
        UIImage *imageFromFile = [UIImage imageWithData:data];
        // 画像をセット
        [self.headerImageButton setImage:imageFromFile
                                forState:UIControlStateNormal];

        // imagePathをmanagedObjectに入れる
        [self.managedObject.imagePath setValue:referenceURL forKey:@"imagePath"];
        NSLog(@"imagePath : %@", referenceURL);

        /*
        // サムネイルを使う場合はassetだけで良いのでもっと楽
        // UIImageに変換
        UIImage* thumbnail = [[UIImage alloc] initWithCGImage:[asset thumbnail]];
        // 画像変更
        [self.headerImageButton setImage:thumbnail
                                forState:UIControlStateNormal];
         */
    } failureBlock:^(NSError *error) {
        // error handling
    }];

    // モーダルビューを閉じる
    [self dismissViewControllerAnimated:YES completion:nil];
}

ちなみに、サムネイルを使う場合はALAssetRepresentationとか書いたりしなくていいので楽です。
[asset thumbnail]で画像が取得できます。

24
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23