Nice programing

iPhone의 ALAsset에서 가져온 URL의 이미지 표시

nicepro 2020. 11. 14. 11:04
반응형

iPhone의 ALAsset에서 가져온 URL의 이미지 표시


장치의 사진 갤러리에있는 파일에 액세스하기 위해 ALAsset Framework를 사용하고 있습니다.

지금까지 썸네일에 액세스하여 표시 할 수 있습니다.
실제 이미지를 이미지보기로 표시하고 싶지만 방법을 알 수 없습니다.

ALAsset 개체의 URL 필드를 사용해 보았지만 실패했습니다.

이것이 어떻게 할 수 있는지 아는 사람이 있습니까?

다음은 축소판에 액세스하여 표 셀에 배치 할 수있는 몇 가지 코드입니다.

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {


  static NSString *CellIdentifier = @"Cell";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
  }
  //here 'asset' represents the ALAsset object


  asset = [assets objectAtIndex:indexPath.row];
       //i am accessing the thumbnail here
  [cell.imageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
  [cell.textLabel setText:[NSString stringWithFormat:@"Photo %d", indexPath.row+1]];

  return cell;
}

API는 규칙을 약간 변경했으며 더 이상 iPhoto 라이브러리에 대한 직접 파일 시스템 액세스 권한을 얻지 못합니다. 대신 다음과 같은 자산 라이브러리 URL을 얻습니다.

assets-library://asset/asset.JPG?id=1000000003&ext=JPG

ALAssetLibrary 객체를 사용하여 URL을 통해 ALAsset 객체에 액세스합니다.

그래서 ALAssetLibrary의 문서에서 이것을 헤더 (또는 소스)에 던지십시오.

typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);

꼭 필요한 것은 아니지만 예쁘게 유지합니다.
그리고 당신의 소스에서.

-(void)findLargeImage
{
    NSString *mediaurl = [self.node valueForKey:kVMMediaURL];

    //
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        CGImageRef iref = [rep fullResolutionImage];
        if (iref) {
            largeimage = [UIImage imageWithCGImage:iref];
            [largeimage retain];
        }
    };

    //
    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"booya, cant get image - %@",[myerror localizedDescription]);
    };

    if(mediaurl && [mediaurl length] && ![[mediaurl pathExtension] isEqualToString:AUDIO_EXTENSION])
    {
        [largeimage release];
        NSURL *asseturl = [NSURL URLWithString:mediaurl];
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:asseturl 
                       resultBlock:resultblock
                      failureBlock:failureblock];
    }
}

주목해야 할 몇 가지 사항은 iOS4 포팅을 시작하기 전에 새로운 블록을 사용한다는 것입니다.

https://www.mikeash.com/pyblog/friday-qa-2008-12-26.html

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html

그들은 당신의 머리를 약간 구부리지 만 알림 선택기 또는 콜백이라고 생각하면 도움이됩니다.

또한

  • findLargeImage반환 할 때 resultblock은 아직 콜백으로 실행되지 않습니다. 따라서 largeImage는 아직 유효하지 않습니다.
  • largeImage 메서드로 범위가 지정되지 않은 인스턴스 변수 여야합니다.

메서드를 사용할 때이 구성을 사용하지만 사용에 더 적합한 것을 찾을 수 있습니다.

[node.view findLargeImage];
UIImage *thumb = node.view.largeImage;
if (thumb) { blah blah }

Thats what I learned while trying to get this working anyway.

iOS 5 update

When the result block fires seems to be a bit slower with iOS5 & maybe single core devices so I couldnt rely on the image to be available directly after calling findLargeImage. So I changed it to call out to a delegate.

@protocol HiresImageDelegate <NSObject>
@optional
-(void)hiresImageAvailable:(UIImage *)aimage;
@end

and comme cá

//
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        CGImageRef iref = [rep fullResolutionImage];
        if (iref) {
            UIImage *largeimage = [UIImage imageWithCGImage:iref];
            [delegate hiresImageAvailable:large];
        }
    };

Warren's answer worked well for me. One useful thing for some people is to include the image orientation and scale metadata at the same time. You do this in your result block like so:

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) 
    {
        UIImage *largeimage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:[rep orientation]];
        [delegate hiresImageAvailable:large];
    }
};

The imageWIthCGImage call in that case has scale and orientation added when it creates a UIImage for you.

[UIImage imageWithCGImage:iref scale:[rep scale] orientation:[rep orientation]];

One trick to note is that if you use [rep fullScreenImage] instead of [rep fullResolutionImage] on iOS 5 you get an image that is already rotated - it is however at the resolution of the iPhone screen - i.e. its at a lower resolution.


Just to combine Warren's and oknox's answers into a shorter snippet:

ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:self.selectedPhotos[i] resultBlock: ^(ALAsset *asset){
    ALAssetRepresentation *representation = [asset defaultRepresentation];
    CGImageRef imageRef = [representation fullResolutionImage];
    if (imageRef) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        imageView.image = [UIImage imageWithCGImage:imageRef scale:representation.scale orientation:representation.orientation];
        // ...
    }
} failureBlock: ^{
    // Handle failure.
}];

I personally like setting my failureBlock to nil.


     NSURL* aURL = [NSURL URLWithString:@"URL here"];

     ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
     [library assetForURL:aURL resultBlock:^(ALAsset *asset)
     {
     UIImage  *copyOfOriginalImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage] scale:0.5 orientation:UIImageOrientationUp];

     cell.backgroundView = [[UIImageView alloc] initWithImage:copyOfOriginalImage];
     }
     failureBlock:^(NSError *error)
     {
     // error handling
     NSLog(@"failure-----");
     }];

just provide the UIReferenceURl you got for the image in photolibrary provided above... its just works fine . . .I diplayed it in

  • UIcollectionView cell

    ..if you just wanna display it in a

  • UIImageView

    means

Change

cell.backgroundView = [[UIImageView alloc] initWithImage:copyOfOriginalImage];

To

imageView.image = copyOfOriginalImage;

참고URL : https://stackoverflow.com/questions/3837115/display-image-from-url-retrieved-from-alasset-in-iphone

반응형