Saving of captured images will leak malloc 48 bytes in strdup frame - iphone

Hi guys I am working on an application in which I am capturing images and also recording video and my application works perfectly but when I using this code
UIImageWriteToSavedPhotosAlbum(image, self,#selector(image:finishedSavingWithError:contextInfo:),nil);
My application Received memory warning in malloc 48 bytes in strdup frame.
And I am using Xcode 4.3.3 with iOS 5.1.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
if (isPhoto == YES) {
viewForAll.hidden = YES;
viewForDisplay.hidden = NO;
isPost1 = YES;
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSData* imageData = UIImageJPEGRepresentation(image,1.0);
UIImage *img1 = [[UIImage alloc] initWithData:imageData];
UIGraphicsBeginImageContext(CGSizeMake(800,1000));
[img1 drawInRect: CGRectMake(0, 0, 800, 1000)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
iView.hidden = NO;
iView.contentMode = UIViewContentModeScaleAspectFit;
iView.image = smallImage;
[img1 release];
}
else if (isVideo == YES) {
viewForAll.hidden = YES;
viewForDisplay.hidden = NO;
isPost1 = YES;
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
videoPath = [[info objectForKey:UIImagePickerControllerMediaURL] retain];
if ([mediaType isEqualToString:#"public.movie"]){
NSLog(#"got a movie");
NSURL *videoForURL = [info objectForKey:UIImagePickerControllerMediaURL];
videoData = [[NSMutableData dataWithContentsOfURL:videoForURL] retain];
videoName = [[videoPath lastPathComponent] retain];
}
UITextField *txtFld;
NSString *eventName;
if ([appDelegate.eventArray count] != 0) {
NSDictionary *dict = [appDelegate.eventArray objectAtIndex:0];
}
else if (isZBar == YES){
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
break;
resultText = [symbol.data retain];
}
}

Related

ios amazon s3 uploading video file

SOS, i need help. I did image uploading on to Amazon S3, and it's working fine, but when I rewrite this code for uploading video it's somethink wrong. Is uploading MOV file, but when i try to play it on browser from url, it's telling me: The image https... cannot be displayed because it contains error.
Here is my code:
- (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller
usingDelegate: (id <UIImagePickerControllerDelegate,
UINavigationControllerDelegate>) delegate{
// Get image picker
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
mediaUI.allowsEditing = YES;
mediaUI.delegate = delegate;
// Display movie files
[controller presentModalViewController:mediaUI animated:YES ];
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
[self dismissModalViewControllerAnimated:YES];
UIImage *image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
fileName = "anyName.MOV";
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
#try {
S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:fileName inBucket:MY_BUCKET];
por.contentType = #"movie/mov";
por.cannedACL = [S3CannedACL publicRead];
por.data = imageData;
[s3 putObject:por];
}
#catch (AmazonClientException *exception) {
NSLog(#"exception %#", exception);
}
}
Pleas point me on my mistake.
Many thanks!!!
Sorted. Problem was with Image object. So I just did get video URL by :
NSURL *image = [info objectForKey:UIImagePickerControllerMediaURL];
Instead
UIImage *image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
And then pass NSData from url, so I did replace line
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
to:
NSData *imageData = [NSData dataWithContentsOfURL:image];
And tataaaaaaaa, problem sorted.

Raw image data from camera

I've been searching this forum up and down but I couldn't find what I really need. I want to get raw image data from the camera. Up till now I tried to get the data out of the imageDataSampleBuffer from that method captureStillImageAsynchronouslyFromConnection:completionHandler: and to write it to an NSData object, but that didn't work.
Maybe I'm on the wrong track or maybe I'm just doing it wrong.
What I don't want is for the image to be compressed in any way.
The easy way is to use jpegStillImageNSDataRepresentation: from AVCaptureStillImageOutput, but like I said I don't want it to be compressed.
Thanks!
This is how i do it:
1: I first open the camera using:
- (void)openCamera
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
(NSString *) kUTTypeMovie, nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
}
else {
lblError.text = NSLocalizedStringFromTable(#"noCameraFound", #"Errors", #"");
}
}
When the picture is taken this method gets called:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Save and get the path of the image
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
// Save the image
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if(!error) {
//Save path and location to database
NSString *pathLocation = [[NSString alloc] initWithFormat:#"%#", assetURL];
} else {
NSLog(#"CameraViewController: Error on saving image : %# {imagePickerController}", error);
}
}];
}
[imagePicker dismissModalViewControllerAnimated:YES];
}
Then with that path i get the picture from the library in FULL resolution (using the "1"):
-(void)preparePicture: (NSString *) filePathPicture{
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *myasset)
{
if(myasset != nil){
ALAssetRepresentation *assetRep = [myasset defaultRepresentation];
CGImageRef imageRef = [assetRep fullResolutionImage];
if (imageRef) {
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 1);
}
}else {
//error
}
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)
{
NSString *errorString = [NSString stringWithFormat:#"can't get image, %#",[error localizedDescription]];
NSLog(#"%#", errorString);
};
if(filePathPicture && [filePathPicture length])
{
NSURL *assetUrl = [NSURL URLWithString:filePathPicture];
ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetUrl
resultBlock:resultBlock
failureBlock:failureBlock];
}
}
Hope this helps you a bit further :-).

MPMoviePlayerController with no content (iOS 5) - The Operation Could Not Be Completed

I have problem with MPMoviePlayerController (self.mp). When I want to access duration property, I get 0, when I want to access thumbnail…, I get nil. On iOS 4 it is OK, iOS 5 it is not.
After all app says to me: The Operation Could Not Be Completed.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]){
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
double hashToNameOfFile = [NSDate timeIntervalSinceReferenceDate] * 1000.0;
NSString *finalPath = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"%.0f.%#", hashToNameOfFile, #"MOV"]];
NSString *finalPathToThumbRetina = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f#2x.%#", hashToNameOfFile, #"jpg"]];
NSString *finalPathToThumb = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f.%#", hashToNameOfFile, #"jpg"]];
// we do need retina now, we use real name for CoreData
NSString *finalImage = [finalPath lastPathComponent];
NSString *finalImageThumb = [finalPathToThumb lastPathComponent];
if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath)){
// Copy it to the camera roll.
UISaveVideoAtPathToSavedPhotosAlbum(tempFilePath, self, #selector(video:didFinishSavingWithError:contextInfo:), tempFilePath);
}
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
// create thumbnail of video
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
NSData *videoData2 = [NSData dataWithContentsOfFile:finalPath];
NSLog(#"LENGTH %i", [videoData2 length]);
NSLog(#"FINAL PATH %#", finalPath);
UIImage *image = [[[UIImage alloc] init] autorelease];
image = [self.mp thumbnailImageAtTime:(NSTimeInterval)1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
NSLog(#"%#", [image size]);
UIImage *thumbImageRetina = [image thumbnailImage:400 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
UIImage *thumbImage = [image thumbnailImage:200 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
NSData *thumbImageRetinaData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImageRetina, 1.0)];
NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImage, 1.0)];
if ( [thumbImageRetinaData writeToFile:finalPathToThumbRetina atomically:YES] ) {
NSLog(#"RETINA THUMB SAVED");
}
else{
NSLog(#"RETINA THUMB NOT SAVED");
}
if ( [thumbImageData writeToFile:finalPathToThumb atomically:YES] ) {
NSLog(#"THUMB SAVED");
}
else{
NSLog(#"THUMB NOT SAVED");
}
// duration of video
double dur = [self.mp duration];
NSLog(#"DUR %f", dur);
TaleRecords *newTaleRecord = (TaleRecords *)[NSEntityDescription insertNewObjectForEntityForName:#"TaleRecords" inManagedObjectContext:_context];
newTaleRecord.content = finalImage;
newTaleRecord.date = [NSDate date];
NSDecimalNumber *latNum = [[NSDecimalNumber alloc] initWithDouble:[self.latitude doubleValue]];
NSDecimalNumber *longNum = [[NSDecimalNumber alloc] initWithDouble:[self.longitude doubleValue]];
newTaleRecord.latitude = latNum; // vertical
newTaleRecord.longitude = longNum; // horizontal
[latNum release];
[longNum release];
newTaleRecord.contentType = [[NSString alloc] initWithFormat:#"cTypeVideo"];
newTaleRecord.thumb = finalImageThumb;
newTaleRecord.duration = [NSNumber numberWithDouble:dur];
newTaleRecord.tale = tales;
tales.record = [newTaleRecord tale].record;
NSError *error = nil;
if (![_context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
[CLController.locationManager stopUpdatingLocation];
[self dismissModalViewControllerAnimated:YES];
}
More simple example
I am doing this:
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
At tempFilePath is real video content and I write it to finalPath. After that I create MPMoviePlayerController instance:
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
But self.mp give me no content. When I want to do [self.mp duration], it returns zero/nil. Path to resource works, but it seems no content is there.
Thank you for your help.
I figured out my problem.
It is like iOS5 is not comfortable with:
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
so instead, if you just use
NSURL *someUrl =[info objectForKey:UIImagePickerControllerMediaURL] ;
and then initial mpmovieplayercontroller with this url, it works fine for me,
which is exactly the opposite of iOS4.
here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"%#",mediaURL);
if (!mymoviePlayer) {
mymoviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:mediaURL];
[mymoviePlayer setControlStyle:MPMovieControlStyleNone];
[mymoviePlayer.view setFrame: videoView.bounds];
[videoView addSubview:mymoviePlayer.view];
}
else
{
[mymoviePlayer setContentURL:mediaURL];
[mymoviePlayer stop];
[mymoviePlayer setInitialPlaybackTime:-1];
}
[self dismissModalViewControllerAnimated:YES];
}

AFGetImageOperation in OpenFlow

What's the correct way to implement AFGetImageOperation for OpenFlow.
AFGetImageOperation *getImageOperation = [[AFGetImageOperation alloc] initWithIndex:i viewController:self];
getImageOperation.imageURL = [NSURL URLWithString:aImage.imageURL];
[loadImagesOperationQueue addOperation:getImageOperation];
[getImageOperation release];
aImage.imageURL has the requested image URL but unsure where the retrieved image is stored?
Thanks
Images are not cached. It fetches the image again and again.
You can cache the image using following methods..
-(NSString *) md5String
{
NSString *md5 = [Utilities md5String:[imageURL absoluteString]];
return md5;
}
-(void) storeImage:(UIImage *)image AtPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
if([manager fileExistsAtPath:path])
{
[manager removeItemAtPath:path error:nil];
}
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:NO];
}
//TODO: //We need to cehck the expiry date as well..
//-(UIImage *) imageFromPath:(NSString *)path Expiry:()
-(UIImage *) loadImageFromPath:(NSString *)path
{
UIImage *image = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if([manager fileExistsAtPath:path])
{
image = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
}
return image;
}
-(NSString *) cachedImagePath
{
NSString *md5 = [self md5String];
NSString *cachedFilePath = [[Utilities applicationCacheDirectory] stringByAppendingPathComponent:md5];
return cachedFilePath;
}
- (void)main {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if (imageURL) {
UIImage *photo = nil;
NSString *cachedFilePath = [self cachedImagePath];
UIImage *image = [self loadImageFromPath:cachedFilePath];
if(image)
{
photo = image;
}
else
{
NSData *photoData = [NSData dataWithContentsOfURL:imageURL];
photo = [UIImage imageWithData:photoData];
[self storeImage:photo AtPath:cachedFilePath];
}
// Create a UIImage from the imageURL.
if (photo) {
[mainViewController performSelectorOnMainThread:#selector(imageDidLoad:)
withObject:[NSArray arrayWithObjects:photo, [NSNumber numberWithInt:photoIndex], nil]
waitUntilDone:YES];
}
} else {
// Load an image named photoIndex.jpg from our Resources.
NSString *imageName = [[NSString alloc] initWithFormat:#"place_holder_bg.png", photoIndex];
UIImage *theImage = [UIImage imageNamed:imageName];
if (theImage) {
[mainViewController performSelectorOnMainThread:#selector(imageDidLoad:)
withObject:[NSArray arrayWithObjects:theImage, [NSNumber numberWithInt:photoIndex], nil]
waitUntilDone:YES];
} else
NSLog(#"Unable to find sample image: %#", imageName);
[imageName release];
}
[pool release];
}

UIImage Saving image with file name on the iPhone

How can I save an image (like using UIImageWriteToSavedPhotosAlbum() method) with a filename of my choice to the private/var folder?
Kenny, you had the answer! For illustration I always think code is more helpful.
//I do this in the didFinishPickingImage:(UIImage *)img method
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
//save to the default 100Apple(Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
UIImageWriteToSavedPhotosAlbum() is only used for saving to the photos camera roll. To save to a custom folder, you need to convert the UIImage into NSData with UIImageJPEGRepresentation() or UIImagePNGRepresentation(), then save this NSData to anywhere you like.
You can use below code, without use of ALAssetsLibrary...
NSString *fileName;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
[self performSelector:#selector(GetImageName) withObject:nil afterDelay:0.5];
}
else
{
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
fileName = [[result firstObject] filename];
}
}];
-(void)GetImageName
{
NSString *str =#"";
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
str = [[fetchResult lastObject] filename];
}
fileName = str;
}