I am trying fetch the picture which is captured by the camera in the iPhone, programmatically. Now, the issue is I am using AVCaptureInput, and other AVFoundation headers and accessing the camera of iPhone instead of simple UIImagePickerViewController because, the program needs a small view inside the main view showing the camera footage. So Now, the issue is I need to fetch the last image I captured. It is being stored in camera roll folder inside library. I need to show it as a preview of last image captured - exactly as how the iPhone's camera does.
You can use the AssetsLibrary framework to access photos in the camera roll.
Something like this should work for getting the last image as a thumbnail:
- (void)updateLastPhotoThumbnail
{
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSInteger numberOfAssets = [group numberOfAssets];
if (numberOfAssets > 0) {
NSInteger lastIndex = numberOfAssets - 1;
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:lastIndex] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
if (thumbnail && thumbnail.size.width > 0) {
photoThumbnailView.image = thumbnail;
*stop = YES;
}
}];
}
} failureBlock:^(NSError *error) {
NSLog(#"error: %#", error);
}];
}
This is assuming that you have assetsLibrary initialized as an instance variable. You can then also observe the notification that is posted when the library changes (could also happen outside of your app):
assetsLibrary = [[ALAssetsLibrary alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateLastPhotoThumbnail) name:ALAssetsLibraryChangedNotification object:nil];
For some reasons above answer is not working for me.
I got it working by using this code.
galleryButton is an instance variable for a uibutton.
- (void)createGalleryButton
{
NSMutableArray *assets = [[NSMutableArray alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger
index, BOOL *stop) {
if(result != nil) {
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
[assets addObject:thumbnail];
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsUsingBlock:assetEnumerator];
}
if(assets.count!=0)
{
UIImage *lastImage = (UIImage *)[assets lastObject];
[self.galleryButton setImage:lastImage forState:UIControlStateNormal];
}
else
{
[self.galleryButton setImage:[UIImage imageNamed:#"camera.bundle/camera-library.png"] forState:UIControlStateNormal];
}
};
[self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock: ^(NSError *error) {
NSLog(#"Failure");
}];
}
to use it
self.galleryButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.galleryButton setFrame:CGRectMake(260, self.view.frame.size.height - 60, 50, 50)];
[self.galleryButton setImage:[UIImage imageNamed:#"camera.bundle/camera-library.png"] forState:UIControlStateNormal];
// assetsLibrary will take time getting all your images at this point. So performItWithDelay
[self performSelector:#selector(createGalleryButton) withObject:nil afterDelay:0.1];
[self.galleryButton addTarget:self action:#selector(showGallery:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.galleryButton];
Related
i write the below code to swipe 2 images. it works fine
but now my task is to swipe more than 2 images horizontally.
and also at the last image if we swipe to the left the first image should appear
how can i achieve this?
-(void)viewDidLoad
{
[super viewDidLoad];
// instantiate gesture recognizer
UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(didSwipe:)];
[imageView addGestureRecognizer:rightSwipe];
UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(didSwipe:)];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
[imageView addGestureRecognizer:leftSwipe];
//setup images
image1 = [UIImage imageNamed:#"1.png"];
image2 = [UIImage imageNamed:#"2.png"];
imageView.image = image1;
}
-(void)didSwipe : (UISwipeGestureRecognizer *) sender
{
UISwipeGestureRecognizerDirection direction = sender.direction;
switch (direction) {
case UISwipeGestureRecognizerDirectionRight:
imageView.image = image2;
break;
case UISwipeGestureRecognizerDirectionLeft :
imageView.image = image1;
break;
default:
break;
}
}
Use below code and you will get desired output.
In the following code you app will use album photos and automatically sets size of the scrolling as per the number of images in album.
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(#"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(#"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
CGSize imageSize;
imageSize.width= imageView.bounds.size.width;
imageSize.height = imageView.bounds.size.height;
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.frame = imageView.frame;
self.scrollView.contentSize = CGSizeMake(imageSize.width * imgArray.count, imageSize.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.bounces=YES;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[self.scrollView flashScrollIndicators];
[self.view addSubview:self.scrollView];
CGFloat xPos = 0.0;
for (UIImage *image in imgArray) {
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.height);
[self.scrollView addSubview:imageView];
xPos += imageSize.width;
// assuming ARC, otherwise release imageView
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20,320 , 420)];
[self getAllPictures];
}
Store your multiple images in NSArray.
Now check condition for swipe right if yes than display image from that array.
and if swipe left than display previous image from that array..
Easy to use for loop and increment operator.
I hope you will get idea.
What is a fast way to load 10-20 fullscreen images from a camera roll, saved photos?
I'm using this code, but to load 10 photos I need to wait about 5-10 seconds. I'm using iPhone 4S.
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if(_savedPhotos.count>=11) *stop = YES;
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *needToStop) {
NSLog(#"%d",index);
if(_savedPhotos.count<11)
{
UIImage *image = [UIImage imageWithCGImage:result.defaultRepresentation.fullScreenImage];
[_savedPhotos addObject:image];
}
else
{
*needToStop = YES;
}
}];
} failureBlock:^(NSError *error) {
NSLog(#"%#",error.description);
}];
The ALAssetsLibrary library will run on a separate thread. So it may take time to communicate with the UI related and other stuff.
So use -performSelectorOnMainThread:withObject:waitUntilDone: inside the ALAssetsLibrary block.
Change your code as below
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *needToStop) {
NSLog(#"%d",index);
UIImage *image = [UIImage imageWithCGImage:result.defaultRepresentation.fullScreenImage];
[self performSelectorOnMainThread:#selector(usePhotolibraryimage:) withObject:image waitUntilDone:NO];
}];
}
failureBlock:^(NSError *error) {
NSLog(#"%#",error.description);
}];
- (void)usePhotolibraryimage:(UiImage *)myImage{
//Do your all UI related and all stuff here
}
Note:Look on this issue too.
I have used demo example of avcapture ,i wanna display image in imagview in viewcontroller after take photo i have use code
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSInteger numberOfAssets = [group numberOfAssets];
if (numberOfAssets > 0) {
NSInteger lastIndex = numberOfAssets-1;
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:lastIndex] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
if (thumbnail && thumbnail.size.width > 0) {
imagviewlastimage.image = thumbnail;
*stop = YES;
}
}];
}
} failureBlock:^(NSError *error) {
NSLog(#"error: %#", error);
}];
to get last image from photo library but i am gatting second last image
and to redirect viewController after pick image i have wrote in
captureManagerStillImageCaptured:(AVCamCaptureManager *)captureManager delegate
ViewController *temp=[[ViewController alloc]init];
temp.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:temp animated:YES];
use as this , how to resolve this ? ya pause screen after take photo
i want to get the count of photos in photoLibrary. Currently, i'am able to get the photoes from photoLibrary and add to myApp's Document directry ONE BY ONE. But what i want is, save all the photos from photoLibrary to Document directry of myApp ALL AT ONCE. Thats why i need the count of photoes in photoLibrary. I've used UIImagePickerControllerSourceTypePhotoLibrary to retrieve the photoes from iPhone photoLibrary.
Any help would be appreaciated..
thanks in advance....
Use ALAssetsLibrary for this:
int imgCount = 0;
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
[self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index,
__block BOOL foundThePhoto = NO;
if (foundThePhoto){ *stop = YES;
}
BOOL *stop) {
/* Get the asset type */
NSString *assetType = [result valueForProperty:ALAssetPropertyType];
if ([assetType isEqualToString:ALAssetTypePhoto]){ NSLog(#"This is a photo asset");
foundThePhoto = YES; *stop = YES;
/* Get the asset's representation object */
ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];
/* We need the scale and orientation to be able to construct a properly oriented and scaled UIImage out of the representation object */
CGFloat imageScale = [assetRepresentation scale];
UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
dispatch_async(dispatch_get_main_queue(), ^(void) {
CGImageRef imageReference = [assetRepresentation fullResolutionImage];
/* Construct the image now */
UIImage *image = [[UIImage alloc] initWithCGImage:imageReference
scale:imageScale orientation:imageOrientation];
//Write image to doument directory
imgCount ++;
}
});
} failureBlock:^(NSError *error) {
} }];
NSLog(#"Failed to enumerate the asset groups."); }];
})
NSLog(#"Total Image Count %d",imgCount);
The code block below counts all videos and photos:
__block int videoCount = 0;
__block int photoCount = 0;
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc]init];
[assetLibrary
enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group == nil) {
// enumeration complete
return;
}
int total = group.numberOfAssets;
[group setAssetsFilter:[ALAssetsFilter allVideos]];
int groupVideoCount = group.numberOfAssets;
videoCount += groupVideoCount;
photoCount += total - groupVideoCount;
}
failureBlock:^(NSError *error) {
// Handle error
}];
I am trying to access iPhone's photo album photo images through ALAssetsLibrary. I could access all the photo albums and get the asset URL of each images on Simulator, via the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(#"See Asset: %#", result);
// assets is a NSMutableArray..
[assets addObject:result];
// Here storing the asset's image URL's in NSMutablearray urlStoreArr
NSURL *url = [[result defaultRepresentation] url];
[urlStoreArr addObject:url];
}
};
void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
}
[self.activity stopAnimating];
[self.activity setHidden:YES];
};
assets = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:assetGroupEnumerator failureBlock: ^(NSError *error) {
NSLog(#"Failure");
}];
urlStoreArr = [[NSMutableArray alloc] init];
}
-(void) GetURLImages
{
for (int i=0; i<[urlStoreArr count]; i++)
{
// To get the each image URL here...
NSString *str = [urlStoreArr objectAtIndex:i];
NSLog(#"str: %#",str);
}
}
It works as expected on iOS 4.0 Simulator, i.e, getting all the images URL's (ex: assets-library://asset/asset.JPG?id=1000000002&ext=JPG). But it doesn't retrieve image URL's on iPod 4.1 device. What could be the problem here? Can someone please help me fix so the code could also work on iPod? I'm totally confused.
Thank you!
Try what I mentioned in my comment or the following
library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
It also depends what photos you want.
void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
}
[self.activity stopAnimating];
[self.activity setHidden:YES];
/* make */ group=nil;//otherwise it is enumerated thrice.
};