[ios] URL에서 UIImage를로드 할 수 있습니까?

이미지의 URL이 있지만 (UIImagePickerController에서 가져옴) 더 이상 이미지가 메모리에 없습니다 (URL은 앱의 이전 실행에서 저장되었습니다). URL에서 UIImage를 다시로드 할 수 있습니까?

UIImage에 imageWithContentsOfFile이 있지만 URL이 있습니다. NSData의 dataWithContentsOfURL :을 사용하여 URL을 읽을 수 있습니까?

편집 1


@Daniel의 대답에 따라 다음 코드를 시도했지만 작동하지 않습니다 …

NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL);
if (photoURL) {
    NSURL* aURL = [NSURL URLWithString:photoURL];
    NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
    self.photoImage = [UIImage imageWithData:data];
    [data release];
}

콘솔을 실행하면 콘솔에 다음이 표시됩니다.

-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'

호출 스택을 보면 URLWithString : relativeToURL :, initWithString : relativeToURL :, _CFStringIsLegalURLString, CFStringGetLength, forwarding_prep_0 , 전달 ,-[NSObject does notRecognizeSelector] 를 호출하는 URLWithString을 호출합니다 .

내 NSString (photoURL의 주소는 0x536fbe0)이 길이에 응답하지 않는 이유가 있습니까? -[NSURL 길이]에 응답하지 않는 이유는 무엇입니까? param이 NSURL이 아닌 NSString이라는 것을 모르십니까?

편집 2


코드의 유일한 문제는 문자열을 URL로 변환하는 것입니다. 문자열을 하드 코딩하면 다른 모든 것이 잘 작동합니다. 따라서 NSString에 문제가 있으며 알아낼 수 없다면 다른 질문으로 들어가야한다고 생각합니다. 이 줄을 삽입하면 (위의 콘솔 로그에서 경로를 붙여 넣었습니다) 제대로 작동합니다.

photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";



답변

이 방법으로 (동기식이지만 컴팩트하게) 할 수 있습니다.

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];

훨씬 더 좋은 방법은 Apple의 LazyTableImage를 사용하여 대화 형 기능을 유지하는 것입니다.


답변

SDWebImage 를 시도해 볼 수 있습니다 .

  1. 비동기식 로딩
  2. 오프라인 사용을위한 캐싱
  3. 로드하는 동안 표시되는 자리 표시 자 이미지
  4. UITableView와 잘 작동

빠른 예 :

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];


답변

그리고 신속한 버전 :

   let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
    var err: NSError?
    var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    var bgImage = UIImage(data:imageData)


답변

당신이 있다면 정말 , 절대적으로 긍정적으로 확인 NSURL 파일 URL을 것을, 즉이 [url isFileURL]귀하의 경우에 true를 돌려 보장, 당신은 간단하게 사용할 수 있습니다 :

[UIImage imageWithContentsOfFile:url.path]


답변

DLImageLoader를 얻고 다음 코드를 시도하십시오.

   [DLImageLoader loadImageFromURL:imageURL
                          completed:^(NSError *error, NSData *imgData) {
                              imageView.image = [UIImage imageWithData:imgData];
                              [imageView setContentMode:UIViewContentModeCenter];

                          }];

누군가에게 도움이 될 수있는 DLImageLoader를 사용하는 또 다른 실제 사례.

PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
    @"http://graph.facebook.com/%@/picture?type=large",
    [aFacebookUser objectForKey:@"id"] ];

__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
   completed:^(NSError *error, NSData *imgData)
    {
    if ( loadMe == nil ) return;

    if (error == nil)
        {
        UIImage *image = [UIImage imageWithData:imgData];
        image = [image ourImageScaler];
        loadMe.image = image;
        }
    else
        {
        // an error when loading the image from the net
        }
    }];

위에서 언급했듯이 요즘 고려해야 할 또 다른 훌륭한 도서관은 Haneke입니다 (불행히도 가볍지 않습니다).


답변

이 코드를 사용해보십시오.로드 이미지를 설정할 수 있으므로 사용자는 앱이 URL에서 이미지를로드하고 있음을 알 수 있습니다.

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
    [yourImageView setContentMode:UIViewContentModeScaleAspectFit];

    //Request image data from the URL:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData)
            {
                //Load the data into an UIImage:
                UIImage *image = [UIImage imageWithData:imgData];

                //Check if your image loaded successfully:
                if (image)
                {
                    yourImageView.image = image;
                }
                else
                {
                    //Failed to load the data into an UIImage:
                    yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
                }
            }
            else
            {
                //Failed to get the image data:
                yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
            }
        });
    });


답변

여기에AsyncImageView 제공된 것을 확인 하십시오 . 좋은 예제 코드이며, “바로”바로 사용할 수도 있습니다.