Saturday, September 14, 2013

Image processes in particular View using Async

Image processes in particular View using Async :-

In xib take one View n give reference of asyncimage

- (void)viewDidLoad
{
    [super viewDidLoad];


scroller =[[CustomScrollBar alloc]initWithFrame:CGRectMake(0,44,
                                        320,460)];
    
    scroller.maximumZoomScale = 4.0;
    scroller.minimumZoomScale = 1.0;
    scroller.clipsToBounds = YES;
    scroller.scrollEnabled = YES;
    scroller.multipleTouchEnabled = YES;
    scroller.userInteractionEnabled = YES;
    scroller.showsHorizontalScrollIndicator = YES;
    scroller.showsVerticalScrollIndicator = YES;
    scroller.scrollsToTop = NO;
    scroller.delegate = self;
    scroller.del = self;
    scroller.contentSize = CGSizeMake(scroller.frame.size.width,
                                      scroller.frame.size.height);
    
    float x = asyImg.bounds.size.width/2;
    float y = (asyImg.bounds.size.height/2);
    asyImg.center = CGPointMake(x, y);
    [asyImg setFrame:CGRectMake(0,44, 320, 290)];
    [scroller addSubview:asyImg];
    self.view.clipsToBounds = YES;
    [self.view addSubview:scroller];
    
       
    [asyImg loadImageFromString:[objImage valueForKey:@"image"] dict:nil];

}

#pragma mark -
#pragma mark scrollView Delegate Methods
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return asyImg;
}
#pragma mark -
#pragma mark Touch Delegate Methods
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 1) {
        [scroller setZoomScale:1.0];
        [self setViewAnimation:CGRectMake(10, 65, 320, 350)];
    }
}
-(void) setViewAnimation:(CGRect)frame {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
    asyImg.frame = self.view.frame;
    scroller.contentSize = self.view.frame.size;
    [UIView commitAnimations];
}


If we want to Post Image :-


-(void)imageUpload
{

  request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:120];
    
    [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSString *strUser = [prefs valueForKey:@"username"];
        [strUser retain];
        NSString * strUserLocal = [strUser stringByAppendingString:@".jpeg"];
        NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:strUserLocal];


[request setPostValue:@"png" forKey:@"type"];
    [request setFile:fetchPath withFileName:imageName andContentType:@"image/ jpg" forKey:@"image"];


    [request setUseCookiePersistence:NO];
    [request setUseSessionPersistence:NO];
    
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request setShowAccurateProgress:YES];
    [request startAsynchronous];


}

OR Other Way to Upload Photo :-


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
  UIImage *sourceImage = self;
  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;
    else
      scaleFactor = heightFactor;
    
    scaledWidth  = width * scaleFactor;
    scaledHeight = height * scaleFactor;
    
    // center the image
    
    if (widthFactor < heightFactor) {
      thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
    } else if (widthFactor > heightFactor) {
      thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
    }
  }
  
  
  // this is actually the interesting part:
  
  UIGraphicsBeginImageContext(targetSize);
  
  CGRect thumbnailRect = CGRectZero;
  thumbnailRect.origin = thumbnailPoint;
  thumbnailRect.size.width  = scaledWidth;
  thumbnailRect.size.height = scaledHeight;
  
  [sourceImage drawInRect:thumbnailRect];
  
  newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  if(newImage == nil) NSLog(@"could not scale image");
  
  
  return newImage ;
}



-(void)imageUpload
{

NSURL *strUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@? action=addComment",Server_URL_MOBICH]];
        
    request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];        
    NSData *imageData = nil;
UIImage *image;
    if (image !=nil) {
            UIImage *newImage = [image imageByScalingProportionallyToSize:CGSizeMake(600, 600)];
            imageData = UIImageJPEGRepresentation(newImage, 0.9);
            [request setData:imageData forKey:@"image"];
            [request setPostValue:@"png" forKey:@"type"];
            [request setPostValue:@"ImageType" forKey:@"comment_type"];
        }
        
    
            [request setRequestMethod:@"POST"];
            [request setTimeOutSeconds:120];
            
            [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
            [request setUseCookiePersistence:NO];
            [request setUseSessionPersistence:NO];
            
            [request setDelegate:self];
            [appDelegate showLoadingView];
            [request setDidFinishSelector:@selector(requestFinished:)];
            [request setDidFailSelector:@selector(requestFailed:)];
            [request setShowAccurateProgress:YES];
            [request startAsynchronous];
        }
}

Way to Save Image in CoreData :-


-(void)btnBarSave
{

if(!self.objinsurance)
    {
        objinsurance =(Insurance *)[appDelegate.objHelper createObjectForEntity:Entity_Insurance];
    }

objinsurance.name = txtName.text;
        objinsurance.insurance_id = txtInsuranceId.text;
   
        if (imageView.image != nil) {
            
            UIImage *image = imageView.image;
            
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSString *strUser = [prefs valueForKey:@"username"];
            [strUser retain];
            NSString * strUserLocal = [objinsurance.insurance_id stringByAppendingString:@".png"];
            
            NSString *imagePath = [[appDelegate applicationDocumentCacheDirectory] stringByAppendingPathComponent:strUserLocal];
            NSLog(@"Path by Image To SAVE :::::>>>%@<<<<<<",imagePath);
            
            NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
            
            if(data != nil) {
                [data writeToFile:imagePath atomically:YES];
                NSLog(@">>>>>>>>>>>>>>>>>>> Image Going To Write <<<<<<<<<<<");
                
               objinsurance.picture = imagePath;
            }
            else
            {
                [[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
                NSLog(@">>>>>>>>>>>>>>>>>>>   Error Writing Image File to Directory      <<<<<<<<<<<");
            }
            
        }else{
            
            NSLog(@"nil");
        }
       
        [appDelegate saveContext];
        [appDelegate showAlertWithTitle:@"" message:@"Data Saved Successfully"];

}


To View Image from CoreData for edit:-


{
txtName.text = objinsurance.name;

  NSData *data = [NSData dataWithContentsOfFile:objinsurance.picture];
    imageView.image = [UIImage imageWithData:data];
}


DBHelper Classes :-


DBHelper.h


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

@interface DBHelper : NSObject {

}


DBHelper.m


@implementation DBHelper

AppDelegate *appDelegate;

-(id) init {
    
    if((self = [super init])) {
        appDelegate = [AppDelegate sharedAppDelegate];
    }
    return self;
}


#pragma mark -
#pragma mark - Creating Object

-(id)createObjectForEntity:(NSString *)entityName
{
    if (entityName!=nil || [entityName isEqualToString:@""])
    {
        return [NSEntityDescription
                insertNewObjectForEntityForName:entityName
                inManagedObjectContext:appDelegate.managedObjectContext];
    }
    else{
        return nil;
    }
}
-(id)createObjectForEntity:(NSString *)entityName context:(NSManagedObjectContext *)aContext
{
    if (entityName!=nil || [entityName isEqualToString:@""])
    {
        return [NSEntityDescription
                insertNewObjectForEntityForName:entityName
                inManagedObjectContext:aContext];
    }
    else{
        return nil;
    }
}


#pragma mark -
#pragma mark - Retrive Object

-(NSMutableArray*) getObjectsforEntity:(NSString *)strEntity ShortBy:(NSString *)strShort isAscending:(BOOL)ascending predicate:(NSPredicate *)predicate
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:strEntity inManagedObjectContext:appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    [fetchRequest setIncludesPendingChanges:NO];
    
    if (strShort)
    {
        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:strShort ascending:ascending];
        
        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
        [sort release];
    }
    if (predicate)
    {
        [fetchRequest setPredicate:predicate];
    }
    NSError *error;
    NSMutableArray *arrAllObjects = (NSMutableArray*)[appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[arrAllObjects retain];
    
    [fetchRequest release];
    
    return arrAllObjects;
}

#pragma mark -
#pragma mark path for Document Directory 

-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}



No comments:

Post a Comment