How can I get the file path from a UIImage?

前端 未结 3 2074
孤街浪徒
孤街浪徒 2021-02-20 08:29

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.

相关标签:
3条回答
  • 2021-02-20 08:40

    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.

    0 讨论(0)
  • 2021-02-20 08:56

    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.
    
    0 讨论(0)
  • 2021-02-20 08:59

    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.

    0 讨论(0)
提交回复
热议问题