Monday, September 29, 2014

Load an Image from existing location and from URL

AsynchImage.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface AsynchImage : UIView{
    
    NSURLConnection* connection;
    NSMutableData* data;
    UIImageView* imageView;
}

-(void)loadImageFromURL:(NSURL*)url;
-(void)loadExistingImage:(UIImage *)image;

@end

AsynchImage.m


#import "AsynchImage.h"

#define ACTIVITY_FRAME CGRectMake(30, 35, 10, 10)
#define ACTIVITYINDICATOR_TAG 999
#define BORDER_COLOR [[UIColor colorWithRed:FLOAT_COLOR_VALUE(200) green:FLOAT_COLOR_VALUE(210) blue:FLOAT_COLOR_VALUE(232) alpha:1.0] CGColor];


@implementation AsynchImage

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)loadExistingImage:(UIImage *)image {
    
    if ([[self subviews] count]>0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];
    }
    
    UIImageView* _imageView = [[UIImageView alloc] init];
    _imageView.frame = CGRectMake(2, 2, self.frame.size.width-4, self.frame.size.height-4); 
    _imageView.image = image; 
    _imageView.layer.borderWidth= 2.5f;
    _imageView.layer.borderColor=BORDER_COLOR
    _imageView.contentMode = UIViewContentModeScaleToFill;
    _imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    [self addSubview:_imageView];
    _imageView =nil;
    [_imageView setNeedsLayout];

    [self setNeedsLayout];
}

- (void)loadImageFromURL:(NSURL *)url{
    
    self.layer.borderColor = BORDER_COLOR
    self.layer.borderWidth = 2.5f;
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc
                                                  initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame=ACTIVITY_FRAME;
    activityIndicator.center=CGPointMake(self.frame.size.width/2, self.frame.size.height/2);

    activityIndicator.tag = ACTIVITYINDICATOR_TAG;
    [self addSubview:activityIndicator];
    [activityIndicator startAnimating];
      
    if (data!=nil) { data = nil; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url                                       
cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:30.0];

    connection = [[NSURLConnection alloc]
                  initWithRequest:request delegate:self];
}

#pragma mark - delegates

- (void)connection:(NSURLConnection *)theConnection
    didReceiveData:(NSData *)incrementalData {
    if (data == nil) {
        data = [[NSMutableData alloc] initWithCapacity:2048];
    }

    [data appendData:incrementalData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
      
    connection=nil;
    
    if ([[self subviews] count]>0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];
    }
   
        imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(0, 0, self.frame.size.width-1, self.frame.size.height-1); 
        imageView.image = [UIImage imageWithData:data];
        //To crop Image
        imageView.image=[self imageByScalingAndCroppingForSize:CGSizeMake(100, 100)];      
  
        int resolution=data.length;
        if(resolution>800) {
            
        }

        imageView.contentMode=UIViewContentModeScaleToFill;
        imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth
                                      UIViewAutoresizingFlexibleHeight);
        [self addSubview:imageView];
        [imageView setNeedsLayout];
        [self setNeedsLayout];   
        imageView = nil;
        // save the image to avoid multiple downloads
       data=nil;
    
       UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self 
                          viewWithTag:ACTIVITYINDICATOR_TAG];
       [activity removeFromSuperview];
}

- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error {
    connection=nil;
   
    UIImage *image = [UIImage imageNamed:@"userImage"];
    [self loadExistingImage:image];
    
    UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self viewWithTag:ACTIVITYINDICATOR_TAG];
    [activity removeFromSuperview];
}

//crop Image
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = imageView.image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.1;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.1;
            }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
         
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


@end

No comments:

Post a Comment