I'm new to iPhone development, I have used UIImagePickerController to capture the image manually, but i want to capture the image automatically, Is it possible to do that.
please help me.
Thanks in advance
Try This. In this I have saved the screen shot in photos album
-(void)screenShotCapture
{
//-- Screen Capture --------------------------------------------------------------------//
UIImage *image = nil;
UIGraphicsBeginImageContext(loginBgImgVw.frame.size);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(375, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:#"%#_Login_%#",providerIdStr,dateToday];
[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];
loginBgImgVw.frame = CGRectMake(10, 0, 1006, 669);
[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label removeFromSuperview];
//=--
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(#"path=--%#",paths);
NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:#"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
if ([screenCapturNameAry count] != 0)
{
if ([screenCapturNameAry containsObject:#"Login"])
{
[imageData writeToFile:savedImagePath atomically:NO];
}
}
UIImageWriteToSavedPhotosAlbum([self loadImage:#"Login_Provider"],self,#selector(image:didFinishSavingWithError:contextInfo:),NULL);
//--------------------------------------------------------------------------------------//
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error == nil)
{
NSLog(#"Login Image saved successfully.");
}
else
{
NSLog(#"Error occurred:%#",[error localizedDescription]);
}
}
You can get the saved image using following method
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
To take the screenshot you can use the following code.
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:#"screen.png" atomically:YES];
For Ratina display device you have to check:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);
Related
I am gettting images from documents directory. it's succesfully getiing. but when it's load on table it appear same images on table.
arrayOfImages = [[NSMutableArray alloc]init];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *stringPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%#",documentsDirectory);
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
for(i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
NSLog(#"%#",strFilePath);
if ([[strFilePath pathExtension] isEqualToString:#"JPG"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSLog(#"%#",imagePath);
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"%#",image);
[arrayOfImages addObject:image];
NSLog(#"%#",arrayOfImages);
}
}
}
For Table i m calling this code
saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
[saveImageView setImage:[arrayOfImages objectAtIndex:indexPath.row]];
[cell.contentView addSubview:saveImageView];
Try this in your cellForRowAtIndexPath method.
static NSString *CellIdentifier = #"Cell";
UIImageView *saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; // You cell initialization
saveImageView.tag = 1000;
[cell.contentView addSubview:saveImageView];
}
((UIImageView *)[cell.contentView viewWithTag:1000]).image = [arrayOfImages objectAtIndex:indexPath.row];
I am using sqlite db to save image path of document directory. Here is my code:
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);
These code save the image in document directory and path in sqlite. Now I want to show image from documents directory to imageview. How to do that? Any idea?
sample code:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(void)loadimage{
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"your image-name"];
UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubView:myimage];
[myimage release];
}
NSString *str = [NSString stringWithFormat:#"%#.jpg",[YourImageArray objectAtIndex:imageCounter]];
or
NSString *str=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"YourImageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullImgNm=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:str]];
[ImageView setImage:[UIImage imageWithContentsOfFile:fullImgNm]];
Hope Your Helpfull
NSString *docDirPath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
NSString *filePath = [docDirPath stringByAppendingFormat:#"myFile.png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
[imageView setImage:image];
If the entire path is stored in the sqlite then you just need to use this
NSString *imapeFilePath = PATH_FROM_DATABASE;
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];
if the file name is stored in the database then use the following
NSString *imapeFilePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:YOUR_IMAGE_NAME];
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];
The below code is not displaying the image which is downloaded from online and written into my application documents directory.
i have checked inside the iphone's simulator documents directory , the downloaded file is exist.
but the image is not displayed.
When trying to add a resources image using UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"]; , the uiimageview displays the image.bu the image which is downloaded from online and stored inside the app directory is not displaying the image.
Pls let me know and thanks
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
//--------------
UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[cell addSubview:imageView1];
}
try this ,this is perfectly working for me:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url1 = [NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:#"savedImage.png"];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath )
{
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubview:imageView1];
}
}
Instead of first converting the file to NSData, you can use
[UIImage imageWithContentsOfFile:filePath]
directly to load a image with given path.
So Im making a two UIscrollview in my view. I'm using Ray Wenderlich's Custom Image Picker. But when I load it, only shows 1 imagepicker. I want to be able to load two image picker. I think Im doing something wrong with initWithCoder part. Cant seem to initialize it properly. Is it possible to have two ivars self. Sorry kinda new to iphoneDev. Thanks for your help.
Here's my whole implementation:
- (id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
_images = [[NSMutableArray alloc] init];
_thumbs = [[NSMutableArray alloc] init];
//THIS IS WHERE I THINK ITS WRONG but the upper part seems to be okay.
_images2 = [[NSMutableArray alloc] init];
_thumbs2 = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void)addImage2:(UIImage *)image {
[_images2 addObject:image];
[_thumbs2 addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void) createScrollView {
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (void) createScrollView2 {
self.slotBg2 = [[UIView alloc] initWithFrame:CGRectMake(362, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView2];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs2.count; ++i) {
UIImage *thumb = [_thumbs2 objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked2:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView2 addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView2 setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (IBAction)buttonClicked:(id)sender {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 2){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 3){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
}
- (IBAction)buttonClicked2:(id)sender {
UIButton *button2 = (UIButton *)sender;
[button2 removeFromSuperview];
[_images2 objectAtIndex:button2.tag];
[_images2 removeObjectAtIndex:button2.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%lu.png", button2.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
[mode1 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
} else if(slotBG == 2 ){
[mode2 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage2:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images2 count]);
[self createScrollView2];
} else if( slotBG == 3){
[mode3 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
}
}
In your createScrollView2 method, you alloc self.slotBg2, but then only reference self.slotBg when adding to your view. Then you add your scrollview2 to the original slotBg.
-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet