I have the following code in place:
- (void)viewDidLoad {
NSString *homeDirectoryPath = NSHomeDirectory();
NSString *imagePath = [homeDirectoryPath stringByAppendingString:#"/graph.png"];
NSLog(#"Image: %#", imagePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath isDirectory:NULL])
{
graph = imagePath;
//[[NSFileManager defaultManager] createDirectoryAtPath:imagePath attributes:nil];
}
'graph' is defined as UIImageView. I'm trying to display the file in the path 'imagePath'. I know the code graph = imagePath is not correct, as the variable 'imagePath' states it contains the path to the image.
How would I display my image located at the specific image path ?
Regards,
Stephen
You'll have to create an imageview object, set it as the image view's image and release the image you created:
UIImage *graphImage = [[UIImage alloc] initWithContentsOfFile: imagePath];
graph.image = graphImage;
[graphImage release];
Related
I want to save displayed UIImageview image in SQL database. I am capturing the image using the camera/albums/library which are displayed in UIImageview. I want to save this image in my SQL database using URL.
Also I need to display this image in another view.
How can I take a path(URL) of my imageview image? How can I store this path(URL) & also store & display into another view?
How to grab the UIImage and write to internal directory:
UIImageView *imageView = "[your image]";
// define your own path and storage for image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
documentPath = [documentPath stringByAppendingPathComponent:#"test.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
[imageData writeToFile:documentPath atomically:YES];
How to get the NSURL/NSString for a file path in internal directory:
// specify fileURL as it is an internal file, don't use URLWithString:
NSURL *fileURL = [NSURL fileURLWithPath:documentDirectory];
// store as a string in database
NSString *fileURLString = fileURL.path;
Please take note that the NSURL for local file is different with normal NSURL.
// for normal URL
NSURL *webURL = [NSURL URLWithString:"http://www.google.com/"];
[webURL absoluteString]; // -> http://www.google.com/
// for local file path URL
NSURL *localURL = [NSURL fileURLWithPath:"/User/path/samplefile.ext"];
[localURL absoluteString]; // -> file://User/path/samplefile.ext
[localURL path]; // -> /User/path/samplefile.ext
just save name of your image in database and store image in phone memory...it will be easy or this way try this line
UIImage *img = [UIImage imageWithContentsOfFile:(the file path)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
I have an application which donwloads several images and stores them on the phone. In total it will probably required around 20 images tops. I need to be able to retrieve any of these images at will depending on what screen the user is on. These images will be stored indefinitely, so I don't want to use temp directory.
At present I have a class named Images with these methods
- (void) cacheImage: (NSString *) ImageURLString : (NSString *)imageName
{
NSURL *ImageURL = [NSURL URLWithString: ImageURLString];
// Generate a unique path to a resource representing the image you want
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: imageName];
// Check for file existence
if(![[NSFileManager defaultManager] fileExistsAtPath: docFile])
{
// The file doesn't exist, we should get a copy of it
// Fetch image
NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
UIImage *image = [[UIImage alloc] initWithData: data];
// Is it PNG or JPG/JPEG?
// Running the image representation function writes the data from the image to a file
if([ImageURLString rangeOfString: #".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImagePNGRepresentation(image) writeToFile: docFile atomically: YES];
}
else if([ImageURLString rangeOfString: #".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound ||
[ImageURLString rangeOfString: #".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImageJPEGRepresentation(image, 100) writeToFile: docFile atomically: YES];
}
}
}
- (UIImage *) getCachedImage : (NSString *)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* cachedPath = [documentsDirectory stringByAppendingPathComponent:imageName];
UIImage *image;
// Check for a cached version
if([[NSFileManager defaultManager] fileExistsAtPath: cachedPath])
{
image = [UIImage imageWithContentsOfFile: cachedPath]; // this is the cached image
}
else
{
NSLog(#"Error getting image %#", imageName);
}
return image;
}
-(void)getImages
{
//example
NSString *image1URL = #"http://test/image1.png";
NSString *image2URL = #"http://test/image2.png";
NSString *image3URL = #"http://test/image3.png";
[self cacheImage:sLogo: #"Image1"];
[self cacheImage:sBlankNav: #"Image2"];
[self cacheImage:buttonLarge :#"Image3"];
}
-(void) storeImages
{
image1 = [self getCachedImage:#"Image1"];
image2 = [self getCachedImage:#"Image2"];
image3 = [self getCachedImage:#"Image3"];
}
So I use the code like this
Images *cache = [[Images alloc]init];
[cache storeImages];
The get images method is called once when the app first starts to get the images, it isn't called again after that, unless the images on the server are updated and I need to retrieve the updated ones.
The code works, but the problem is when I navigate to a screen that uses it, there is a very slight delay before the screen loads as it is loading the images.
My application is a tabbed application, so it begins on tab 1, I click tab 2 which implements the code, there will be a slight pause the first time it loads. It doesn't last very long, but it is noticeable and is very annoying. After that it is fine, as it is already loaded. However with navigation controller, every time you move from the first VC to the second VC, the method will be called again, so each time you navigate the delay will be there.
The images are not very big, biggest one is 68kb, others are much smaller than that. At present I am just testing with 5 images. Is there a more efficient way of storing and retrieving images, or am I doing something wrong with my code? I need to be able to retrieve these images without any noticeable delay in order for my application to remain fluid and not jerky or clunky.
Thanks in advance!!
You have two options to do the image loading work on a background thread - use Grand Central Dispatch or NSInvocationOperation. GCD might be considered the cleaner of the two:
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(q, ^{
//load images here
dispatch_async(main, ^{
// show on main thread here
});
});
you have delay because you're downloading data synchronously
// NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
Try some smart library like SDWebImage:
it lets you download image asynchronously while you still can display a local image (a proxy image). By the way, you still get cache image for free. So even if u are on local, you can still catch previously downloaded images
https://github.com/rs/SDWebImage
A must have
Having weird problem with my NSDocumenDirectory saving.
Here is a sneak preview:
First I pick images ( in my imagePickerViewController):
in my PreviewController:
So at first try, it was okay.
Then I revisit the imagePickerViewController to add another image:
in my PreviewController:
This is where the problem occurs. At the image above, it recopies the last image from the old preview (like a duplicate). I dunno what Im doing wrong in my codes. But Im saving it when a file exist. Kindly see:
for (int i = 0; i < info.count; i++) {
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%d.png", i]];
if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
NSLog(#"file doesnt exist");
} else {
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
NSLog(#"saving at:%#",savedImagePath);
}
}
What I need is to just reAdd AGAIN the same image with the new one.
Same as, like the last preview.
The four images are passed in the sequence that they show in the preview, so in the first example the orange cat is third, and in the second example, the orange cat is fourth. The new image isn't saving because it is third, and you already have a file named "firstSlotImages2.png". If you re-save each image without checking if the file exists, you should get the result you are looking for.
There's a key in the media info: UIImagePickerControllerMediaURL which returns an NSURL, convert it to a string and get the the lastPathComponent. Use this as the file name to save to the directory you are saving it to. You can then save the reference to these images by saving this same file name either in an NSMutableArray, or an NSMutableDictionary
hi i created a new group in my code and put the all images in that now resources\CountryFlags is the path i am doing this
NSString *fileName = countryInfo.ImageUrl;
CCSprite *flag ;
NSString * fullPath = [[NSBundle mainBundle] pathForResource: [fileName stringByDeletingPathExtension]
ofType: [fileName pathExtension]
inDirectory: #"CountryFlags"];
if (fullPath)
{
UIImage *theImage = [UIImage imageWithContentsOfFile: fullPath];
if (theImage)
{
flag = [CCSprite spriteWithCGImage: [theImage CGImage] key: fileName];
flag.position = ccp(200, 265);
flag.scale = .255;
}
}
but fullpath always got nil and not getting the code so any one have any idea how to solve this
I think it's because there is no "CountryFlags" folder in your app's bundle. XCode does not copy directory structure of resources unless folders are added as folder references (blue folder icons in project navigator, not yellow).
I need to Read a Image from the specific URL .
It works fine with WWW . but it returns a nil when the URL pointing the Local Folder .
// Works
NSString *sampleData = #"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg";
// Returns nil
NSString *sampleData = #"USER/user2/...";
Note :
I am changing the NSString to NSURL and creating the UIImage .
NSURL *url = [NSURL URLWithString: data];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
You are supplying a relative pathname for the file URL. That relative pathname is interpreted relative to the current working directory of the running application, which isn't guaranteed to be anything in particular, and so is almost certainly not what you want.
You can either supply an absolute path - one that starts with '/' - or set your app's current working directory to something explicit, like your user's Documents folder.
you probably should have a look into the NSBundle Class.
Methods like
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
or
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
is probably what you want
First of all, you can NOT read file from such path you given: "USER/user2/...", the file must in your App bundle or in your App's sandbox.
Second, check your path string if there was some texts need to be encoded in URL. Try:
NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Also, if the url is not nil, you should also check if your [NSData dataWithContentsOfURL:url]; is returning nil. If so, it means your URL is not correct so the method cannot find your file.
P.S., You are mistyping your image create code, you should call alloc before imageWithData:.
You should do something like to get the local url :
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, nameOfFile];
and finaly, load your image :
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
Try these instead
NSString *path = #"USER/user2/.../xxx.xxx";
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isFileExist = [fileManager fileExistsAtPath:path];
UIImage *image;
if (isFileExist) {
image = [[UIImage alloc] initWithContentsOfFile:path];
}
else {
// do something.<br>
}