ios UIImage:imageWithContentsOfFile来袭了

时间:2012-08-10 12:31:54

标签: objective-c uiimageview uiimage

这里我从url下载图像并将其保存到缓存目录中,我们从缓存路径中获取了图像,但是它被触发以获取图像。是否有任何替代解决方案从localpath获取图像

在这里,我分享了从localpath获取图像的代码:

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath,[[imageurl componentsSeparatedByString:@"/"]lastObject]];
UIImage *image = [UIImage imageWithContentsOfFile:path];

1 个答案:

答案 0 :(得分:0)

您应该创建一个NSObject类来处理图像的下载和缓存。实施例

接口文件

        #import <Foundation/Foundation.h>

            @interface ImageCache : NSObject
            {
             UIImage *background;
            }
   @property (nonatomic,retain) UIImage *background;         
            -(void)getImages;
            -(void) storeImages;
            -(void) clearCache;

    @end

实施

    @implementation ImageCache

        @synthesize background;


            - (void) cacheImage: (NSString *) ImageURLString : (NSString *)imageName
            {
                NSURL *ImageURL = [NSURL URLWithString: ImageURLString];

                // Generate a unique path to a resource representing the image you want

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *docDir = [paths objectAtIndex: 0];
                NSString *docFile = [docDir stringByAppendingPathComponent: imageName];

                // Check for file existence
                if(![[NSFileManager defaultManager] fileExistsAtPath: docFile])
                {
                    // The file doesn't exist, we should get a copy of it

                    // Fetch image
                    NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];

                    UIImage *image = [[UIImage alloc] initWithData: data];

                    // Is it PNG or JPG/JPEG?
                    // Running the image representation function writes the data from the image to a file
                    if([ImageURLString rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
                    {

                        [UIImagePNGRepresentation(image) writeToFile: docFile atomically: YES];

                    }
                    else if
                    (
                            [ImageURLString rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound || 
                            [ImageURLString rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound
                    )
                    {
                        [UIImageJPEGRepresentation(image, 100) writeToFile: docFile atomically: YES];
                    }
                }
            }

            - (UIImage *) getCachedImage : (NSString *)imageName
            {

                NSArray *paths = NSSearchPathForDirectoriesInDomains
                (NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString* cachedPath = [documentsDirectory stringByAppendingPathComponent:imageName];

                UIImage *image;

                // Check for a cached version
                if([[NSFileManager defaultManager] fileExistsAtPath: cachedPath])
                {
                    image = [UIImage imageWithContentsOfFile: cachedPath]; // this is the cached image
                }else
                {
                    NSLog(@"Error");
                }

                return image;
            }

        -(void)getImages
        {    
//I just googled background image and took first image I found for this example
         NSString *backgroundURL = @"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg";  
        [self cacheImage:backgroundURL: @"Background"];

        }

    -(void) clearCache
    {
    //If you ever need to clear the cache for whatever reason, good to have a method to handle it    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex: 0];
        NSString *docFile1 = [docDir stringByAppendingPathComponent: @"Background"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:docFile1 error:NULL];

    }

    -(void) storeImages
    {
        background = [self getCachedImage:@"Background"];
    }

@end

在示例中,我给了我一个图像。但你明白了我的想法。现在,如果您想下载并存储该图像。只需在ViewController中导入ImageCache类,然后调用

ImageCache *cacheMe = [[ImageCache alloc] init];
   [cache getImages];
    [cacheMe storeImages];
    UIImageView *image = [[UIImageView alloc] initWithImage:[cacheMe background]];

这就是你需要做的一切。如果你有一个专门用于缓存的课程,那就更容易了。希望有所帮助!!

编辑:更新忘了两行代码。我自己测试过,现在应该正常工作