Download Image and UIButton BG image - iphone

I am trying to do download some images from server then , set these images as background image for some UIButtons .
so first downloading images :
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSString *str = [NSString stringWithFormat:urlMag1,urlMag2,nil];
NSData *data = [NSData dataWithContentsOfFile:str];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:path atomically:YES];
UIImage *imgMag1 = [UIImage imageNamed:#"i224_mag2.png"];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
but nothing happens !!,and how can I check to if these images are in directory to avoid more downloading
I would be grateful if you help me to solve this
thanks !
EDITED
#Fernando Cervantes
I created a method to set buttons BG images something like this , but I don't know why does not work !
- (UIImage *)loadImages :(NSString *)fileNames ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
[[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileNames, extension]]];
return 0;
}
and set BG images :
- (void)buttonsBGImage {
UIImage * bgMag2 = [self loadImages:#"i224_mag2" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[mag2 setBackgroundImage:bgMag2 forState:UIControlStateNormal];
}
but actually nothing happens ! even I check the file and it's in app directory

The following approach might help you out a bit.
Save
-(void) saveFile:(NSString *)fileName ofType:(NSString *)extension fromURL:(NSString *)fileIndexPath inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileIndexPath]];
[data writeToFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension] atomically:YES];
}
Check
-(BOOL) checkIfFileExists:(NSString *)fileName ofType:(NSString *)extension inDirectoryPath:(NSString *)directoryPath {
bool result;
if ([[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileName, extension]]]) {
result = TRUE;
} else {
result = FALSE;
}
return result;
}
Set
UIButton * button = [[UIButton alloc] init];
UIImage * backgroundImage = [self loadImage:#"YourImageName" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[button setImage:backgroundImage forState:UIControlStateNormal];
-Edited-
I believe your problem is that you are returning 0 in your loadImages method. Instead of returning the image itself.
This is how I accomplished it:
Load
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}

[UIImage imageNamed:#"i224_mag2.png"]; // it is only for bundle. You should use
[UIImage imageWithContentsOfFile:path]
or
[UIImage imageWithData:data];
Update:
I use category for UIButton class.
- (void)loadImage:(NSString *)URL withActivityIndicator:(BOOL)hasActivity refreshObject:(UIView *)refresh{
// load image from cache cutted
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *loadedImage = [UIImage imageWithData:image];
// add image to cache cutted
[self setImage:loadedImage forState:UIControlStateNormal];
});
});
}

You are making NSData using dataWithContentsOfFile: API. you should use dataWithContentsOfURL instead.
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSData *image1 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]];
NSData *image2 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag2]];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
Usually [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]]; will freeze UI until image downloading complete.

Related

Sharing an image to Instagram on iOS

I am trying to open one of my pictures on instagram but every time I push the action button (as you can see from my code) it shows instagram icon and when I push the Instagram icon the app crashes. What am I doing wrong? I have been stuck on this for a while.
interface ViewController : UIViewController <UIDocumentInteractionControllerDelegate>{
IBOutlet UIImageView *onlyImageVIew;
IBOutlet UIImageView *myImageView;
}
#property (nonatomic, retain) UIDocumentInteractionController *docController;
-(IBAction)actionButton:(id)sender;
#end
-(IBAction)actionButton:(id)sender {
NSURL *instagramURL = [NSURL URLWithString:#"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Image.ig"];
UIImage *image = [UIImage imageNamed:#"01.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
NSURL *imageUrl = [NSURL fileURLWithPath:savedImagePath];
NSLog(#"%#",imageUrl);
UIDocumentInteractionController *docController = [[UIDocumentInteractionController alloc] init];
docController.delegate = self;
docController.UTI = #"com.instagram.photo";
docController.URL = imageUrl;
//[docController setURL:imageUrl];
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
}
Here is the crash when I implemented the bool function
2013-02-10 13:34:46.206 share to instagram[2197:907] file://localhost/var/mobile/Applications/0AABBF7B-F479-44E7-BA7F-B0FAA636F1CB/Documents/Image.ig
hope below code works for you.
-(void)ShareInstagram
{
UIImagePickerController *imgpicker=[[UIImagePickerController alloc] init];
imgpicker.delegate=self;
[self storeimage];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
CGRect rect = CGRectMake(0 ,0 , 612, 612);
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/15717.ig"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
dic.UTI = #"com.instagram.photo";
dic.delegate=self;
dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
dic.delegate=self;
[dic presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
// [[UIApplication sharedApplication] openURL:instagramURL];
}
else
{
// NSLog(#"instagramImageShare");
UIAlertView *errorToShare = [[UIAlertView alloc] initWithTitle:#"Instagram unavailable " message:#"You need to install Instagram in your device in order to share this image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
errorToShare.tag=3010;
[errorToShare show];
}
}
- (void) storeimage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"15717.ig"];
UIImage *NewImg=[self resizedImage:imageCapture :CGRectMake(0, 0, 612, 612) ];
NSData *imageData = UIImagePNGRepresentation(NewImg);
[imageData writeToFile:savedImagePath atomically:NO];
}
-(UIImage*) resizedImage:(UIImage *)inImage: (CGRect) thumbRect
{
CGImageRef imageRef = [inImage CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
// There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
// see Supported Pixel Formats in the Quartz 2D Programming Guide
// Creating a Bitmap Graphics Context section
// only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
// and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
// The images on input here are likely to be png or jpeg files
if (alphaInfo == kCGImageAlphaNone)
alphaInfo = kCGImageAlphaNoneSkipLast;
// Build a bitmap context that's the size of the thumbRect
CGContextRef bitmap = CGBitmapContextCreate(
NULL,
thumbRect.size.width, // width
thumbRect.size.height, // height
CGImageGetBitsPerComponent(imageRef), // really needs to always be 8
4 * thumbRect.size.width, // rowbytes
CGImageGetColorSpace(imageRef),
alphaInfo
);
// Draw into the context, this scales the image
CGContextDrawImage(bitmap, thumbRect, imageRef);
// Get an image from the context and a UIImage
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* result = [UIImage imageWithCGImage:ref];
CGContextRelease(bitmap); // ok if NULL
CGImageRelease(ref);
return result;
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate
{
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
interactionController.delegate = self;
return interactionController;
}
- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller
{
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action
{
// NSLog(#"5dsklfjkljas");
return YES;
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller performAction:(SEL)action
{
// NSLog(#"dsfa");
return YES;
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application
{
// NSLog(#"fsafasd;");
}
This code works for me.
Best of Luck.
First, make sure your image isn't nil after the imageNamed: call.
Then, make sure the imageData isn't nil after the UIImagePNGRepresentation call.
Finally, check the result of writing the image to the file before attempting to use it:
BOOL writingResult = [imageData writeToFile:savedImagePath atomically:YES];
if(writingResult == NO)
{
NSLog(#"Failed to write to %#",savedImagePath);
return;
}
It's possible your file isn't being written, and so trying to share a file that doesn't exist is causing your crash.

Image is not being shown when using UIImage imageWithData:NSData dataWithContentsOfFile

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.

How to display a image downloaded from URL in iPhone?

I am downloading a image from the url and saving it. When i try to display the same image in UI using ImageView I am not able to do it. So please suggest what changes I need to be done in the following code.
Thank you.
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.objectgraph.com/images/og_logo.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png::::%#", docDir);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSString *sss = [docDir stringByAppendingString:#"/test.png"];
imageView1.image = [UIImage imageNamed:sss];
NSLog(#"------%#",sss);
[image release];
}
UIImage *theUIimage = [UIImage imageNamed:sss];
image = [[UIImageView alloc] initWithImage:theUIimage];
[imageView1 addSubview:image];
How is your imageView initalized? Make sure to also specify the imageView.frame.
e.G.:
CGRect frame = CGRectMake(xPositionInView,yPositionInView,
image.size.width,image.size.height);
imageView.frame = frame;

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];
}

iPhone : creating Texture2D much slower when image loaded from file in app's Documents, why?

Slower than what? slower than creating the same textures from an image loaded from the app bundle.
How much slower ? 80 times slower on iPhone, similar ratio (but faster overall) on Mac.
My example below shows loading an image with imageNamed: ; creating textures from the first image ; saving image to a file in the app's Documents directory ; loading an image from that file ; creating textures from the second image.
Images are 640x640 png, 100 textures 64x64 are created in each case.
Creation times are 0.51 s vs. 41.3 s.
Can anyone explain this huge difference, and point me to ways and means of speeding up the second case, to make it as fast as the first, if possible ?
Rudif
#import "Texture2D.h"
#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; NSLog(#"Time = %f", stop-start);
#interface UIImage (CS_Extensions)
-(UIImage *) imageAtRect:(CGRect)rect;
+(NSString *) documentsDirectory;
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename;
+(UIImage *) imageFromDocumentsFile:(NSString *)filename;
+(BOOL) documentsFileExists:(NSString *)filename;
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture;
#end;
#implementation UIImage (MiscExt)
-(UIImage *)imageAtRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
UIImage* subImage = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);
return subImage;
}
+(NSString *) documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
+(UIImage *) imageFromDocumentsFile:(NSString *)filename {
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename {
if (image != nil) { // save to local file
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
//You can write an NSData to the fs w/ a method on NSData.
//If you have a UIImage, you can do UIImageJPEGRepresentation() or UIImagePNGRepresentation to get data.
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager fileExistsAtPath:path];
if (ok) {
NSLog(#"%s : written file %#", __FUNCTION__, path);
}
else {
NSLog(#"%s : failed to write file %#", __FUNCTION__, path);
}
}
}
+(BOOL) documentsFileExists:(NSString *)filename {
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path];
return exists;
}
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture {
NSLog(#"%s -> ", __FUNCTION__);
START_TIMER;
for (int x = 0; x < 9; ++x) {
for (int y = 0; y < 9; ++y) {
UIImage *ulCorner = [image640x640 imageAtRect:CGRectMake(x*64,y*64,64,64)];
texture[y*10+x] = [[Texture2D alloc] initWithImage:ulCorner];
}
}
END_TIMER;
NSLog(#"%s <- ", __FUNCTION__);
}
#end
-(void) test {
Texture2D *texture1[100];
Texture2D *texture2[100];
// compare texture creation from a bundled file vs Documents file
{
UIImage *imageBundled = [UIImage imageNamed:#"bivio-640x640.png"];
[UIImage createTexturesFromImage:imageBundled texture:texture1];
[UIImage saveImage:imageBundled toDocumentsFile:#"docfile.png"];
BOOL ok = [UIImage documentsFileExists:#"docfile.png"];
UIImage *imageFromFile = [UIImage imageFromDocumentsFile:#"docfile.png"];
[UIImage createTexturesFromImage:imageFromFile texture:texture2];
}
}
When you built your project, XCode optimises PNGs that you put in resources.
This article explains it in details: http://iphonedevelopment.blogspot.com/2008/10/iphone-optimized-pngs.html