【问题标题】:How to save image URL to photo library and subsequently use the saved image如何将图像 URL 保存到照片库并随后使用保存的图像
【发布时间】:2011-12-09 07:07:30
【问题描述】:

我正在为我的应用实施“在线图片搜索”功能。我需要的流程如下:

1) 获取用户想要使用的图片 url

2) 将图片(通过 URL)保存到手机相册

3) 通过图像选择器控制器检索保存的图像并打开移动和缩放屏幕

4) 使用从相册中检索到的图像。

任何人都可以告诉我在获取图像 URL 后如何执行上述步骤吗?

【问题讨论】:

    标签: objective-c ios image url uiimagepickercontroller


    【解决方案1】:

    您可以使用此代码将图像保存在相册中

        UIImageWriteToSavedPhotosAlbum(yourImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
    
    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
    {
        if (error != NULL)
        {
            // handle error
        }
        else 
        {
            // handle ok status
        }
    }
    

    现在为了在另一个线程中执行代码,我会写这样的代码

    // load data in new thread
    [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
    

    您可以在代码、按钮或任何其他 UIKit 控件中的任何位置使用此方法。然后,您将需要能够完成艰苦工作的方法。

    - (void)downloadImage
    {
    
        // network animation on
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
        // create autorelease pool
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    
       // save image from the web
        UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"your_image_address.com"]]], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
        [self performSelectorOnMainThread:@selector(imageDownloaded) withObject:nil waitUntilDone:NO ];  
    
        [pool drain];       
    
    }
    
    - (void)imageDownloaded
    {
    
        // network animation off
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
        // do whatever you need to do after 
    }
    

    【讨论】:

    • 您好,感谢您的回复!您能否告诉我如何将图像 url 转换为图像格式,从而我可以执行上面的代码将其写入相册?
    • 如果你是从网上下载的,那么你可以用 UIImage *yourImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"your_image_address.com"]]]; 进行初始化,如果你正在下载它在主线程中的所有其他内容都将等待它完成,因此例如指示器视图不会旋转。
    • 抱歉,这可能与原来的问题有点偏差。但是我怎样才能在不同的线程中触发呢?
    • 这太棒了。非常感谢您的时间和帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多