如何从 UIImagePickerController 获取缩略图或可保存路径以用于 UIImageView?

发布于 2024-10-11 16:08:54 字数 348 浏览 10 评论 0原文

有人可以解释或展示一些示例代码,说明在用户使用 UIImagePickerController 选择照片后如何使用将缩略图放入 UIImageView 中吗?

假设我想将缩略图设置为表视图单元格的图像。当用户按下该单元格时,将显示图像选择器,并且用户选择其设备上已有的图像。我还想保存该缩略图的路径,以便下次显示视图时,可以显示正确的缩略图。

我能够显示图像选择器,并且我的委托正确获取所选图像,但我想要缩略图的路径,并且我想使用该路径加载缩略图(即我想保存路径)。 我今天搜索了几个小时但还没弄清楚。也许我不理解 ALAsset,或者可能是其他东西,但我找不到任何对我有帮助的例子。我以前从未使用过图像选择器或 ALAsset,所以我对此完全陌生。

Could somebody please explain or show some sample code of how I can use get a thumbnail to be put into a UIImageView after the user selects a photo with UIImagePickerController?

Let's say I want to set a thumbnail as the image of a table view cell. When the user presses the cell, the image picker is shown and the user selects an image that is already on their device. I also want to save the path to that thumbnail so that the next time the view is displayed, the proper thumbnail can be shown.

I am able to display an image picker and my delegate get's the chosen image correctly, but I want the path to the thumbnail, and I want to load the thumbnail using that path (i.e. I want to save the path).
I've searched for hours today and haven't figured this out. Perhaps I'm not understanding ALAsset, or maybe it is something else, but I can't find any examples that are helping me. I have never used the image picker or ALAsset before now, so I'm completely new at this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野心澎湃 2024-10-18 16:08:54

//如果您正在阅读本文并查看下面的评论并想??WTF??这是因为我正在编辑我的原始答案,而不是发布两个答案,希望事情会更干净。重要的是要知道 ALAssetsLibrary 是 iOS 4.x 的东西。

下面的代码将获取资产库 URL,然后从缩略图表示中创建 UIImage。虽然我直接使用 asset-library url,但同样的代码没有理由不能通过将字符串表示形式转换为 NSURL 来满足 imageURL 分配。免责声明:此代码可能会泄漏或更糟糕的情况,但它回答了原始发布者的问题,并且希望具有价值。

下面的代码大量借鉴了这个 Stack Overflow 问题 基本上涵盖了同一主题。除了此处的代码之外,我还包含了其他问题中引用的 AssetsLibrary.framework 和 ALAssetsLibrary typedef。

整个技巧是您无法直接从资产库引用 NSURL。我认为(尽管我不知道)它以某种方式引用数据存储而不是文件,因此从 URL 返回的数据不是直接 NSData,因此您不能以旧方式使用它。

代码中有一个UIImageView,名为photo。希望其他一切都很容易弄清楚。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSLog(@"%@",imageURL);
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        CGImageRef iref = [myasset thumbnail];
        if (iref) {
            UIImage *theThumbnail = [UIImage imageWithCGImage:iref];
            [[self photo] setImage:theThumbnail];

        }
    };


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

    if(imageURL)
    {
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:imageURL 
                       resultBlock:resultblock
                      failureBlock:failureblock];
    }

    [self dismissModalViewControllerAnimated:YES];
}

如果您不需要缩略图但确实想要完整照片,您只需将 AssetForURLResult 块中的代码更改为如下所示:

       ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];

我们可以将该练习留给用户。

祝你好运,希望这有助于你解决问题。

//If you are reading this and look at the comments below and think ??WTF?? it is because I am editing my original Answer instead of posting two Answers in hopes that things will be cleaner. It is important to know that ALAssetsLibrary is an iOS 4.x thing.

The code below will function to take an asset-library URL and then make a UIImage out of the thumbnail representation. Though I use the asset-library url directly there is no reason that this same code couldn't begin by transforming a string representation into a NSURL in order to satisfy the imageURL assignment. Disclaimer: this code probably leaks or something worse, but it answers the original poster's question and is hopefully of value.

The code below is borrowing heavily on this Stack Overflow question that covers basically this same topic. In addition to the code here, I have included AssetsLibrary.framework and the ALAssetsLibrary typedefs referenced in the other question.

The whole trick is that you cannot reference the NSURL from an asset-library directly. I think (though I don't know) that it is somehow referencing a data store instead of a file so the data returned from the URL isn't straight NSData so you cannot use it the old way.

There is a UIImageView in the code that is called photo. Hopefully everything else is easy to figure out.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSLog(@"%@",imageURL);
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        CGImageRef iref = [myasset thumbnail];
        if (iref) {
            UIImage *theThumbnail = [UIImage imageWithCGImage:iref];
            [[self photo] setImage:theThumbnail];

        }
    };


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

    if(imageURL)
    {
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:imageURL 
                       resultBlock:resultblock
                      failureBlock:failureblock];
    }

    [self dismissModalViewControllerAnimated:YES];
}

If you don't want the thumbnail but do want the full photo, you will just change the code in the AssetForURLResult block to something like this:

       ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];

We can leave that exercize for the user.

Good luck, hope this helps clear things up for you.

番薯 2024-10-18 16:08:54

我现在已经大致明白了。我遇到的困难是理解块,主要是块的语法让我很难理解它们是什么以及它们如何工作。

在 UIImagePickerController 的委托中,当用户选择图像时,您可以使用以下方法获取资源库中图片的路径: 使用

NSURL *path = [info objectForKey:UIImagePickerControllerReferenceURL];

该对象,您可以使用以下代码获取全尺寸图像或缩略图:

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        // Gets the full size image
        self.fullSizeImage = [UIImage imageWithCGImage:iref];
    }

    // Gets the thumbnail
    self.thumbnail = [UIImage imageWithCGImage:[myasset thumbnail]];
};

ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
    NSLog(@"in failureblock, got an error: %@",[myerror localizedDescription]);
};

ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init];
[assetsLib assetForURL:urlForImage resultBlock:resultblock failureBlock:failureblock];

此页面确实帮助我理解了块:iOS 4 中的块
另请参阅显示从 iPhone 中的 ALAsset 检索到的 URL 中的图像

I've got it mostly figured out now. The difficulty I had was understanding Blocks, mostly the syntax of Blocks made it difficult to understand what they are and how they work.

In the delegate for the UIImagePickerController, when the user has selected an image, you can get the path to the picture in the assets library using:

NSURL *path = [info objectForKey:UIImagePickerControllerReferenceURL];

With that object, you can get the full size image or a thumbnail using the following code:

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        // Gets the full size image
        self.fullSizeImage = [UIImage imageWithCGImage:iref];
    }

    // Gets the thumbnail
    self.thumbnail = [UIImage imageWithCGImage:[myasset thumbnail]];
};

ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
    NSLog(@"in failureblock, got an error: %@",[myerror localizedDescription]);
};

ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init];
[assetsLib assetForURL:urlForImage resultBlock:resultblock failureBlock:failureblock];

This page really helped me understand Blocks: Blocks in iOS 4
See also display image from URL retrieved from ALAsset in iPhone

萧瑟寒风 2024-10-18 16:08:54

保存 URL 可能会出现问题:

  1. 至少在 iOS 4.x 中,不能保证 URL 是唯一的。如果用户删除/添加图片,它们可以重复使用,这显然很常见。因此,您保留的 URL 将来可能会指向不同的图片!
  2. 当用户更新到 iOS 5 时,URL 不再有效。啊!!!苹果重写了照片库,但没有向后兼容性。

Saving the URL can be problematic:

  1. at least in iOS 4.x, the URLs is not guaranteed to be unique. They can be reused if user deletes/add pictures, which is obviously common. So, the URL you kept can point to a different picture in the future!
  2. When the user updates to iOS 5, the URLs are no longer valid. UGH!!! Apple has rewritten Photo Library, with no backward compatibility.
月亮是我掰弯的 2024-10-18 16:08:54

您可以将从 imagePicker 选择的图像保存到文档目录中,而不是从选择器中引用它
这是可用于保存图像的代码。在用户从选择器中选择照片时调用的回调方法中实现此方法

 NSFileManager   fileManager    = [NSFileManager defaultManager];

    NSArray*  output_PDF_paths  =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString* output_PDF_documentsDirectory = [output_PDF_paths objectAtIndex:0];
    NSString* output_PDF_ABSOLUTE_PATH  = [output_PDF_documentsDirectory stringByAppendingPathComponent:@"ImageName.png"];  

    BOOL success_new = [UIImagePNGRepresentation(ProfilePhotoselected) writeToFile:previewPagePath atomically:YES];

//这里“ProfilePhotoselected”是您从选择器中作为 callabck 方法中的参数获取的图像

You can save the image you select from imagePicker into Documents Directory instaed of referencing it from the picker
Here is the code you can use for saving image. Implement this method in the callback method invoked when user selects a photo from the picker

 NSFileManager   fileManager    = [NSFileManager defaultManager];

    NSArray*  output_PDF_paths  =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString* output_PDF_documentsDirectory = [output_PDF_paths objectAtIndex:0];
    NSString* output_PDF_ABSOLUTE_PATH  = [output_PDF_documentsDirectory stringByAppendingPathComponent:@"ImageName.png"];  

    BOOL success_new = [UIImagePNGRepresentation(ProfilePhotoselected) writeToFile:previewPagePath atomically:YES];

//Here the "ProfilePhotoselected" is the image which you get from the picker as a argument in your callabck method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文