Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the file path from a UIImage?

Usually it's the other way around, you use the path to display the image. I was wondering if you can get the path if you already have the image.

like image 312
Mirror318 Avatar asked Nov 27 '13 19:11

Mirror318


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is UIImage?

An object that manages image data in your app.

What is use of UIImageView?

Whenever you want an image in a view controller, you use a UIImageView. A UIImageView contains a UIImage, which is the raw bitmap, and allows you to configure how you want to scale or crop the image.

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in . h file and allocated in init method, I need to set image in viewDidLoad method.


3 Answers

if you already have the image i.e. have added the file to your resources, you can use this to get the file path;

NSString *string = [[NSBundle mainBundle] pathForResource:@"IMAGE_FILE_NAME" ofType:@"jpg"]; // or ofType:@"png", etc.
like image 139
Joel Balmer Avatar answered Oct 02 '22 04:10

Joel Balmer


I don't believe it is possible to get it directly from UIImage.

Best way is to save the image in a directory, then you will have the file path.

//image is your UIImage;

if (image != nil)
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"test.png" ];
    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
}

path will be your filepath.

like image 36
Brianjs Avatar answered Oct 02 '22 04:10

Brianjs


Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

like image 42
Holly Avatar answered Oct 02 '22 04:10

Holly