Thursday, June 14, 2012

Save UIImage from url

You can save image from url  to documents folder
/* save image from url */
- (void) saveImageFromURL:(NSString *) folder file:(NSString *)fileName url:(NSString*)fileURL {   
    NSString *filePath;
    [self removeFileFromDocuments:folder file:fileName];
    NSString* documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    if([folder length] == 0) {
        filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    } else {
        filePath = [[[[documentsDirectory stringByAppendingString:@"/"] stringByAppendingString:folder] stringByAppendingString:@"/"] stringByAppendingString:fileName]; 
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
   
    if(![fileManager fileExistsAtPath:filePath]) {       
        // Get an image from the URL below
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]]];
        NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data writeToFile:filePath atomically:YES];
        [image release];
    }
   
}
You can be too get & save by NSURLRequest
- (UIImage*) getSynchronousImage:(NSString*)fileURL {
    NSError * err;
    NSURLResponse * response;
   
    NSString *strURL = [fileURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];

    NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest
                                                  returningResponse:&response
                                                              error:&err];
    if( !receivedData ){
        /* Handle error */
        NSLog(@"Error:%@",[err description]);
    }
    /* Check response */
    UIImage *image = [[UIImage alloc] initWithData:receivedData];
                      
    return image;

}



Split file by block size

Split file with block size
/* splitFile */
- (NSUInteger)splitFile:(NSString *)filename chunkSize:(NSUInteger)chunkSize {
    NSUInteger chunksWritten;
   
    NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
    NSData *fileData = [NSData dataWithContentsOfFile:filename];
    NSString *newFileName;
    NSRange dataRange;
    for (chunksWritten = 0; chunksWritten * chunkSize < [fileData length]; chunksWritten++) {
        newFileName = [filename stringByAppendingPathExtension:[NSString stringWithFormat:@"%03d", chunksWritten]];
        dataRange = NSMakeRange(chunksWritten * chunkSize, MIN(chunkSize, [fileData length] - chunksWritten * chunkSize));
        if (![fm createFileAtPath:newFileName contents:[fileData subdataWithRange:dataRange] attributes:nil]) {
            NSLog(@"Error writing chunk #%d", chunksWritten);
            break;
        }
    }
    return chunksWritten;
}


Export UIImage to file

Export to file:
- (void) exportImageToFile:(NSString*) path image:(UIImage*) image {
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [imageData writeToFile:path atomically:YES];
}

Get all frame from movie with avfoundation

You can get all frame from movie but need memory large 
/* Get all frame from movie */
- (NSMutableArray*) getAllFrameFromMovie:(NSString*) folderName file:(NSString *) fileName {
    [mainBusy startWithTitle:@"Movie Processing ..."];
    /* Setting input movie */
    NSString* video_inputFileName = fileName;
    NSString* video_inputFilePath = [Utilities documentsPath:folderName file:video_inputFileName];
    NSURL*    video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];    
   
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:video_inputFileUrl options:options];;
   
    Float64 durationFrames = CMTimeGetSeconds([asset duration]) * 24.0;
   
    AVMutableComposition *myComp = [AVMutableComposition composition];
   
    AVMutableCompositionTrack *compositionVideoTrack = [myComp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
   
    NSError *error = nil;
    BOOL ok = NO;
   
    NSMutableArray *frameArray = [[NSMutableArray alloc] init];
   
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:myComp];
    NSError *err = nil;
   
    for (int i = 0; i < floor(durationFrames); i++) {
       
        CMTime startTime = CMTimeMake(i, 24);
        CMTime endTime = CMTimeMake(i+1, 24);
       
        CMTimeRange myRange = CMTimeRangeMake(startTime, endTime);
       
        AVAssetTrack *sourceVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
        ok = [compositionVideoTrack insertTimeRange:myRange ofTrack:sourceVideoTrack atTime:kCMTimeZero error:&error];
        if (!ok) {
            // Deal with the error.
        }
       
        CMTime time = CMTimeMake(0,1);
        UIImage *currentImg = [UIImage imageWithCGImage:[generate copyCGImageAtTime:time actualTime:nil error:&err]];
       
        /* Processing frame  */
        UIImage *img = [self drawText:@"TRAVELsec"
                             fontSize:30 inImage:currentImg atPoint:CGPointMake(10,430) rotatetext:90];
        UIImage *imgs = [self drawText:[NSString stringWithFormat:@"Frame :%d",i]
                              fontSize:30 inImage:img atPoint:CGPointMake(10,470) rotatetext:90];
        [frameArray addObject:imgs];
       
    }
   
    NSLog(@"This video is calculated at %f Frames..",durationFrames);
    NSLog(@"You made a total of %i Frames!!",[frameArray count]);
    [generate release];
   
    return frameArray;
}

Using avfoundation framework get movie size

You can get movie size :

/* get  naturalSize */
- (CGSize) getMovieSize:(NSString*) folderName file:(NSString *) fileName {
   
    /* Setting input movie */
    NSString* video_inputFileName = fileName;
    NSString* video_inputFilePath = [Utilities documentsPath:folderName file:video_inputFileName];
    NSURL*    video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];   
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:video_inputFileUrl options:nil];
   
    return asset.naturalSize;
}

How to rotate & scale uiimage

Rotate & scale image :
/* rotate image and scale */
- (UIImage*) scaleAndRotateImage:(UIImage *)image orients:(UIImageOrientation) orients {
    int kMaxResolution = 320; // Or whatever
   
    CGImageRef imgRef = image.CGImage;
   
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
   
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }
   
    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = orients;//image.imageOrientation;
    switch(orient) {
           
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
           
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
           
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
           
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
           
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
           
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
           
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
           
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
           
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
           
    }
   
    UIGraphicsBeginImageContext(bounds.size);
   
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
   
    CGContextConcatCTM(context, transform);
   
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

Iphone sort array

You can sort NSArray : 

/* Sort array */
- (NSArray*) sortArray:(NSArray*) dArray ascending:(BOOL)bl {
   
    /* Sort data  */
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@""
                                                  ascending:bl] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray;
    sortedArray = [dArray sortedArrayUsingDescriptors:sortDescriptors];
    return sortedArray;
}