Using UIImageView to make a app like iPhone's Photo Galerry - iphone

Please help me !
I make an app like a slide show with back, previous button to change Image one by one. But when I using large image it crash. Now I'm using 64 jpg pics , size~20kb/1pic.
Help me or I die ! (U can add nick hoangtuanfithou, please)
code like that :
//Init Image Array
-(void)InitImageArray1
{
myAnimationImages1 = [[NSMutableArray alloc] init];
for ( int i = 0; i < 24; i++ )
{
NSAutoreleasePool *poolArray=[[NSAutoreleasePool alloc] init];
NSString *fileName = [NSString stringWithFormat:#"001 (%d)",i];
image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:#”jpg”]];
[myAnimationImages1 addObject:image];
[poolArray release];
}
}
//Change Image
self.mainImage.image = [self.myAnimationImages1 objectAtIndex:animationImageArrIndex];

see page control sample of apple,or see scrolling madness available at github.

Related

How to improve images loading issues. is there any cache like solution

I have built an iOS app using Parse.com.
In my app i have displayed a lot of data from network.
To load the data speedily i used cache kPFCachePolicyCacheThenNetwork. It loads data fine but while scrolling images are takes some amount of time to load.
First white image and then image loads.
Is there any solution like cache to display images in imageviews with out interruption.
Thanks.
You can use SDWebImage for doing this.
Also you can use NSCache for caching purpose.
Yes you can use AFNetworking UIImageview category and you are sorted
you can also disable caching of a particular image usually needed if you edit an existing image and then dwnload it from same URL, by manipulagting its
-(void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
as mentioned in this blog
An other option could be ASImageView with facility to refresh cache.
I write the code with the help of gcd , you just have to pass the object of imageView and pass the url , it manages all the things, like cache.
-(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{
strUrl = [strUrl encodeUrl];
NSString* theFileName = [NSString stringWithFormat:#"%#.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
actView.frame = frameToCenter;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *dataFromFile = nil;
NSData *dataFromUrl = nil;
dataFromFile = [fileManager contentsAtPath:fileName];
if(dataFromFile==nil){
dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
}
dispatch_sync(dispatch_get_main_queue(), ^{
if(dataFromFile!=nil){
imgView.image = [UIImage imageWithData:dataFromFile];
}else if(dataFromUrl!=nil){
imgView.image = [UIImage imageWithData:dataFromUrl];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
if(filecreationSuccess == NO){
NSLog(#"Failed to create the html file");
}
}else{
imgView.image = [UIImage imageNamed:#"NO_Image.png"];
}
[actView removeFromSuperview];
[actView release];
[imgView setBackgroundColor:[UIColor clearColor]];
});
});
}
Here is the code for loading image in background . check this Code
you should use EGOImageLoading(EGOImageLoading) for lazy loading of images and can save images using NSUserDefaults.
It is best way i advice as i have used it in many projects.
Sorry to say it, but Parse is already doing all these things. Parse uses AFNetworking to get the images, puts them in an NSCache, and uses disk caching very aggressively so that redundant network trips are completely avoided (the version is part of the URL, so Parse doesn't even need to use an if-modified-since GET).
The biggest issue you might be encountering is that PFFile throttles downloads to only download 3 images at a time. After experimentation this was the best number because it ensured incremental feedback to the user and avoided a nasty issue where some iOS devices would get very poor performance after too many threads. The best advice I could offer you would be to prefetch some images if possible. As mentioned earlier, PFFile images are very aggressively cached. The kPFCachePolicy... stuff only affects queries which might grow stale; the images those queries point to are always cached (though only initially downloaded on demand).

how to display image in UIImageView in a specifc block of window in iphone

I have a window in which I want to display an image in a specific block of that window. The image is retrieved from the local XML file. I parsed the XML file and got the image value in the log, but I don't know how to put it in that specific block. The below image pasted for the reference.
The arrow mark represents that within this UIImageView I need to get the image. Also, I doubt that I need to mention any name for reference to UIIMageView in storyboard. Suggest me an idea.
Edited
My parser code:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Sample.xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
[xmlParser setDelegate:theParser]
After this I am using this code for getting image:
UIImage *image = [UIImage imageWithContentsOfFile:#"/Users/administrator/Desktop/imageApp/resources/Main_pic1.png"];
After this I don't know how to continue.
Yes, you have to create IBOutlet in .h file
like IBOutlet UIImageView *imgview; and connect imgview with your UIImageview from xib.
After that you can set image to image view.
NSURL *URL = [NSURL URLWithString:[your url which u get form local xml]];
NSData *imageData = [NSData dataWithContentsOfURL:URL];
UIImage *image = [UIImage imageWithData:imageData];
imgview.image=image;
Ttry this, It may help you.
You can directly pass the url image to Uiimageview by :
YourImageView.image = [UIImage imageWithContentsOfURL:YourUrl];
It's possible to do the equivalent by going through NSData, but it's a bad idea. Instead, the image should be downloaded asynchronously using NSURLConnection, and only once it's fully downloaded should it be converted into a UIImage and assigned to the image view.
Save all your urls in an say NSMutableArry *UrlArray then
int x = 0;
int y = 10;
for (int i = 0; i< [UrlArray]; i++)
{
UIImageView *imageView = [[[UIImageView alloc]initWithFrame:CGRectMake(3+x,y, 80,
80)]autorelease];
imageView.backgroundColor = [UIColor blueColor];
if (x >= 300)
{
x = 0;
y = y+imageView.frame.size.height+3;
imageView.frame = CGRectMake(x+3 , y, 80, 80);
}
CIImage *beginImage = [CIImage imageWithContentsOfURL:[UrlArray ObjectAtIndex:i]];
imageView.image = [UIImage imageWithCIImage:beginImage];
x = x+imageView.frame.size.width+5;
[self.view addSubview:imageView];
}
will do the work i guess;

How to ignore #2x images

I have the following code below to populate an array with images:
NSString *fileName;
myArray = [[NSMutableArray alloc] init];
for(int i = 1; i < 285; i++) {
fileName = [NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i];
[myArray addObject:[UIImage imageNamed:fileName]];
NSLog(#"Loaded image: %d", i);
}
In my resources folder i have #2x versions of each of these images. Is there a way (programmatically) that I can ignore the #2x images on retina devices and populate the array with the non-#2x images?
EDIT 1:
I've edited my code to use NSData:
myArray = [[NSMutableArray alloc] init];
for(int i = 1; i < 285; i++) {
fileName = [NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
UIImage *regularImage = [UIImage imageWithData:fileData];
[myArray addObject:regularImage];
}
falling.animationImages = MYArray;
This is crashing my app with the error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'. Am i using the NSData object wrong?
I believe the question amounts to "How do I bypass the automatic #2x image loading?"
You need to take a path it can't follow. You could pass the contents of each file using NSData dataWithContentsOfFile:options:error: to UIImage imageWithData: This way, imageWithData won't know where the data came from, let alone that there's a 2x version.
I think the NSData technique should work, but you need to get the path from your bundle, you can't just give the filename as a string like that.
Try:
filename = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i] ofType:nil];
Try this...
//This string will have #"#2x.png"
NSString *verificationString = [myString substringFromIndex:[myString length] - 7];
if(![verificationString isEqualToString:#"#2x.png"])
{
//NOT EQUAL...
}

IPhone Development - Setting Background Image For IPad From A Downloaded Image

I am new to this and have searched a lot this week. I am trying to set a background image from a file I have downloaded from a url. I need to save the image for later. Specially if I am not connected to the internet I can still show this image.
I have validated by printing out the contents of the directory that the file exists. This is one of many code that I have tried to make the image appear in the background.
nNSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentPath = [docDir stringByAppendingFormat:#"/mainback.png"];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",documentPath);
if ([[NSFileManager defaultManager]fileExistsAtPath:documentPath]) {
NSData *data = [NSData dataWithContentsOfFile:documentPath];
UIImage *image = [[UIImage alloc] initWithData:data];
NSLog(#"WHAT - %f,%f",image.size.width,image.size.height);
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:documentPath]];
self.view.backgroundColor = background;
[background release];
}
The code finds the image in the directory but I cannot set the image to the background. Please help.
Thanks
Use a UIImageView (Apple documentation linked) instead of doing what you are trying to do with UIColor.
It'll be a lot more straightforward and less problematic.

How to refresh images using HJCache?

I'm trying to display an image from a webcam in my app using HJCache.
The webcam refreshes its image every 5 minutes.
I'd like to have a refresh button, so that users could click it to see a new image (if available).
My code so far:
-(void)viewDidLoad {
// init HJObjManager
objMan = [[HJObjManager alloc] initWithLoadingBufferSize:6 memCacheSize:20];
// refresh button
UIBarButtonItem *buttonRefresh = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshPhoto:)];
self.navigationItem.rightBarButtonItem = buttonRefresh;
[buttonRefresh release];
NSURL *url = [NSURL URLWithString: #"http://webcamurl"];
img1.url = url;
[self.objMan manage:img1];
}
-(IBAction) refreshPhoto: (id) sender {
// ?
}
Could you give me an hint on how to implement refreshPhoto?
Edit: ender pointed me to emptyCache. If I understand it ok, it should be used by HJMOFileCache, so my code now is:
-(void)viewDidLoad {
NSString *documentsDirectory;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"imageCache/"];
objMan = [[HJObjManager alloc] initWithLoadingBufferSize:6 memCacheSize:20];
HJMOFileCache* fileCache = [[[HJMOFileCache alloc] initWithRootPath:documentsDirectory] autorelease];
fileCache.fileCountLimit = 100;
fileCache.fileAgeLimit = 300; // 5 min
objMan.fileCache = fileCache;
// refresh button
UIBarButtonItem *buttonRefresh = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshPhoto:)];
self.navigationItem.rightBarButtonItem = buttonRefresh;
[buttonRefresh release];
NSURL *url = [NSURL URLWithString: #"http://webcamurl"];
img1.url = url;
[self.objMan manage:img1];
[super viewDidLoad];
}
-(IBAction) refreshPhoto: (id) sender {
[self.objMan.fileCache emptyCache];
[self.objMan manage:img1];
}
It doesn't work though, when I click the refresh button nothing happens, the image does not refresh.
Any idea?
Edit: ender suggested that maybe the cache files do not get deleted by emptyCache (if I understand it right), but it looks like they actually do.
From NSLog before and after the emptyCache:
2011-09-09 16:57:33.842 Ready dir before emptyCache: (
"http:__www.meteogallipoli.it_cam_cam1.jpg"
)
2011-09-09 16:57:33.845 Loading dir before emptyCache: (
)
2011-09-09 16:57:33.856 Ready dir after emptyCache: (
)
2011-09-09 16:57:33.859 Loading dir after emptyCache: (
)
"Ready" and "Loading" are the directories where objMan stores files already downloaded and being downloaded, respectively.
Maybe the problem is in making objMan manage the image again?
I think its because you configured the object manager with both a file cache and a memory cache. When you empty the file cache, there are still images in the memory cache? Try instanciating the object manager with
if you only have an image, you can use [objMan emptyCache];
If you want to refresh only an image, you can save it in a different dir and use this method instead:
[objMan deleteAllFilesInDir:path];
Of course, you will have to make the query again:
[self.objMan manage:img1];