UIImage stretching for unknown reason - ios

EDIT: This only happens in the phone. It works fine in the simulator.
I am having a weird issue that I can't seem to rectify.
In the app I am building you can add and replace a profile photo and here is what is happening.
When you either select an image from your library or take a new one with the camera, you are returned to your profile view and you can see the new image.
Here it is with a temp image.
But when I go back to the main nav and then return to the profile page, the image is wider than it should be.
I am at a real loss here. The code to call each image is virtually identical.
// Code after initial image selection
UIImage *image = [info valueForKey: UIImagePickerControllerOriginalImage];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:NO];
profileImage.image = image;
//Code after returning to the page.
UIImage *image = [[UIImage alloc] initWithContentsOfFile:directoryWithProfilePicName];
profileImage.image = image;
Any thoughts would be great.
UPDATE 1:
// Creating directoryWithProfilePicName.
NSString *localDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *profilePicName = [NSString stringWithFormat:#"/%#", profilePic];
NSString *directoryWithProfilePicName = [localDirectory stringByAppendingString:profilePicName];
// Creating the image view.
#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)
if (IS_IPHONE5) {
profileImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 335, 300)];
} else {
profileImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 335, 210)];
}
UPDATE 2:
- (void)takeNewPhotoFromCamera {
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
controller.allowsEditing = NO;
controller.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
controller.delegate = self;
[self.navigationController presentViewController: controller animated: YES completion: nil];
}
-(void)choosePhotoFromExistingImages {
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
controller.allowsEditing = NO;
controller.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypePhotoLibrary];
controller.delegate = self;
[self.navigationController presentViewController: controller animated: YES completion: nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.navigationController dismissViewControllerAnimated: YES completion: nil];
NSString *uuidString = [[NSUUID UUID] UUIDString];
NSString *imageName = [NSString stringWithFormat:#"%#.jpg", uuidString];
UIImage *image = [info valueForKey: UIImagePickerControllerOriginalImage];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)];
NSLog(#"Pic Name: %#", imageName);
NSLog(#"Image Size: %f x %f", image.size.width, image.size.height);
NSLog(#"picture Taken.");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:NO];
[UIView saveNewPhoto:imageName forPetID:pIDint];
profileImage.image = image;
profileImage.contentMode = UIViewContentModeScaleAspectFit;
}

I'm guessing your problem is caused by your UIImageView's content mode.
theImageView.contentMode = UIViewContentModeScaleAspectFit;
Make sure you are using ScaleAspectFit, otherwise your UIImageView will default to UIViewContentModeScaleToFill.

Related

Setting Image from gallery in iOS

I select an image from gallery and display on UIImageView but when I click back button and again open push to the image view controller that image is empty.
What should I do to remain same image on UIImageView after logout also?
I have used this code:
- (void)viewDidLoad {
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile1=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
NSData *data=[NSData dataWithContentsOfFile:fullPathToFile1];
[[self teacherImg]setImage:[UIImage imageWithData:data]];
[data writeToFile:fullPathToFile1 atomically:YES];
}
- (IBAction)selectImg:(id)sender {
pickerController = [[UIImagePickerController alloc]init];
pickerController.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
UIImage * img = [info valueForKey:UIImagePickerControllerEditedImage];
teacherImg.image = img;
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
NSData *data=UIImagePNGRepresentation(teacherImg.image);
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
[data writeToFile:fullPathToFile atomically:YES];
imagePicker.allowsEditing = YES;
imagePicker.delegate = self;
[[self teacherImg]setImage:image];
[self dismissViewControllerAnimated:YES completion:nil];
}
In viewDidLoad() method you need to load image from doc. dir.
NSString *myGrrabedImage1 = #"myGrrabedImage1.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1 = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
Method 1:
NSData *imgData = [NSData dataWithContentsOfFile: fullPathToFile];
UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
Method 2:
UIIMage *image = [UIImage imageWithContentsOfFile: fullPathToFile];
[imgView setImage: image];
You should read the image data and set the ImageView image in the viewWillAppear method.
viewDidLoad is called only once, after the view has been loaded from the xib/storyboard
Try this way;
- (void)viewDidLoad {
NSString *myGrrabedImage1 = #"myGrrabedImage1.png";
NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1 = [path objectAtIndex:0];
NSString *pathFile = [documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
UIIMage *image = [UIImage imageWithContentsOfFile: pathFile];
[teacherImg setImage: image];
}
- (IBAction)selectImg:(id)sender {
pickerController = [[UIImagePickerController alloc]init];
pickerController.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
UIImage * img = [info valueForKey:UIImagePickerControllerEditedImage];
teacherImg.image = img;
NSData *data=UIImagePNGRepresentation(teacherImg.image);
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
[data writeToFile:fullPathToFile atomically:YES];
[[self teacherImg]setImage:image];
[self dismissViewControllerAnimated:YES completion:nil];
}

How to show and play captured photos and videos,Audios in ios [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i am beginner in Ios and in my project i have given facility for users capturing photos and videos and Audios from camera and i am storing their "paths" in array lists and i am displays them in one table-list so for everything is ok
But here my main requirement is when i click table-list rows then if there is image file it must be shows or if there is video it must be play audio also have to play as like videos for this i have written some code here photos and videos are playing fine but audio files giving problem what did i do here wrong?
my code:-
#import "ViewController2.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController2 ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
AVAudioRecorder * _audioRecorder;
AVAudioPlayer * player;
}
#end
#implementation ViewController2
#synthesize maintablelist;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
maintablelist.delegate = self;
maintablelist.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
- (IBAction)takeAudio:(id)sender {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSetting
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
}
else {
NSLog(#"ok");
[arr_media addObject:soundFilePath];
[_audioRecorder record];
[maintablelist reloadData];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[maintablelist reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[maintablelist reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
}
#end
Here, I have modified your piece of code. First of all, there is no need of different arrays to store images and videos. You can access it from one. Simillarly, there is no need of storing media types in two different arrays. You can do it by one array.
Moreover, to save images and videos to document directory, you need to write those file to specific path. You will then be able to access them.
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
}
#end
#implementation ViewController
#synthesize tbl;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
tbl.delegate = self;
tbl.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
-(IBAction)takeAudio
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[arr_media addObject:soundFilePath];
[_audioRecorder record];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *Dir = [paths objectAtIndex:0];
// NSString *fileName = [NSString stringWithFormat:#"Pic-%lf.png", [[NSDate date] timeIntervalSince1970]];
//
// //this path if you want save reference path in sqlite
// NSString *pngPath = [NSString stringWithFormat:#"%#/%#",Dir,fileName];
//
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[tbl reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[tbl reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
// NSString*thePath=[[NSBundle mainBundle] pathForResource:[arr_media objectAtIndex:indexPath.row] ofType:#"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
#end
Your issue is that you are not saving the captured images/photos and simply trying to use the paths. Please take a look at Apple Documentation on how to use it. You can save them in your project's Documents directory, save the file name and path as you are doing then use those paths for rendering/playing later on.
As a side note, in your implementation, there are few lines of code that you are executing after [picker dismissViewControllerAnimated:YES completion:nil]. I would advise to utilize completion block here and load your table view once image picker view dismissal is complete. This avoid run time crashes.
EDIT: On OP request
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #“image1.png”];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile: filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
// Save your model data and reload table here
}];
}
}

How to copy video from iPhone album without compression?

When I tried to copy a video from album to app using UIImagePickerController, the video is compressed.
When the video imported via Photos app on Mac, the ten-second long video is:
1920x1280 ~22MB
After the video is imported into app, then copied via iTunes Sharing, the compressed video is:
1280x720 ~6.3MB
How can I import video into app in original resolution and quality?
Code:
- (void)importVideo:(id)sender {
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePickerController.allowsEditing = YES;
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if (CFStringCompare((__bridge_retained CFStringRef)mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [paths firstObject];
NSString *filename = [folder stringByAppendingPathComponent:self.uniqueFilename];
BOOL success = [videoData writeToFile:filename atomically:NO];
NSLog(#"Write to file %#", success ? #"OK" : #"Error");
}
}
Once a PHAsset is obtained via GMImagePicker, it can be saved by:
for (PHAsset *asset in assetArray) {
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset
options:options
resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
if ([avAsset isKindOfClass:[AVURLAsset class]]) {
NSURL *videoURL = [(AVURLAsset *) avAsset URL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [paths firstObject];
NSString *filename = [folder stringByAppendingPathComponent:#"foo.mp4"];
[videoData writeToFile:filename atomically:NO];
}
}];
}

UIImage returns nil (xcode5)

My UIImage is nil if I try to test this block of code:
- (IBAction)sliderBrightness:(id)sender {
UIImage *inputImage = imgView.image;
GPUImageBrightnessFilter *stillImageFilter = [[GPUImageBrightnessFilter alloc] init];
GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:inputImage];
[stillImageSource addTarget:stillImageFilter];
[stillImageFilter useNextFrameForImageCapture];
[stillImageSource processImage];
UIImage *currentFilteredVideoFrame = [stillImageFilter imageFromCurrentFramebuffer];
[self->imgView setImage:currentFilteredVideoFrame];
}
UPDATE:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
imgView.image = [info objectForKey:#"UIImagePickerControllerEditedImage"];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
toolbar.hidden = NO;
UIImage *image1 = imgView.image;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image1.png"];
[UIImagePNGRepresentation(image1) writeToFile:cachedImagePath atomically:YES];
}
if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
toolbar.hidden = NO;
UIImage *image1 = imgView.image;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image1.png"];
[UIImagePNGRepresentation(image1) writeToFile:cachedImagePath atomically:YES];
}
if (picker.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
toolbar.hidden = NO;
UIImage *image1 = imgView.image;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image1.png"];
[UIImagePNGRepresentation(image1) writeToFile:cachedImagePath atomically:YES];
}
else{
toolbar.hidden = NO;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Debugger (inputImage is nil):
I hope someone can help me.
Thanks in advance for your help.
I'm using xcode 5.1.1 (iOS Simulator: iPhone 4-inch; 64-Bit; iOS7.1)
If (as you say in comments) the problem is that inputImage is nil, the problem is external to the code you've posted. Either imgView is itself nil, or it points to a UIImageView instance that hasn't yet had its image set. Put a breakpoint on the line:
UIImage *inputImage = imgView.image;
and inspect imgView to determine which of those possibilities is the problem.

Camera image not saving in document directory

I have written code to capture image from camera and i want to save that image in document directory. I have done the code but i think the image is not storing document directory. Because when i retrieve the images the camera images is not in documents directory,my code:
- (IBAction)takePhoto {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *cameraImage = info[UIImagePickerControllerEditedImage];
self.tempView.image = cameraImage;
[_chosenImages addObject:_tempView.image];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
id n = [array3 lastObject];
NSLog(#"The id is=%#",n);
NSError *error;
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",n]];
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSInteger anIndex = 0;
for (UIImage *anImage in _chosenImages) {
NSString *anImageName = [NSString stringWithFormat:#"%d.png", anIndex++];
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", dataPath, anImageName];
NSLog(#"the path is=%#",anImagePath);
NSData *anImageData = UIImagePNGRepresentation(anImage);
[anImageData writeToFile:anImagePath atomically:YES];
// While fetching NSDocumentDirectory Path it will give in the array format. So instead of giving NSString you need to give NSArray.. check below code
// Try this
NSArray * aDocumentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [aDocumentsDirectory objectAtIndex:0];
NSString *finaldocPath = [docPath stringByAppendingPathComponent:fileName];

Resources