xcode Swift 3 中来自路径或文件名的 UIImage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46072110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:13:01  来源:igfitidea点击:

UIImage from path or filename in Swift 3

iosswiftxcodeuiimage

提问by Andrea

i have a bunch of images in my App's Documents Directory. i want to load one of them in an UIImage that i have in my view. this is what i do:

我的应用程序的文档目录中有一堆图像。我想在我认为的 UIImage 中加载其中一个。这就是我所做的:

myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil

I also tried to init the image using:

我还尝试使用以下方法初始化图像:

myImage.image = UIImage(contentsOfFile: imagePath) //this also doesn't work but the path i got starts (at least in the sim) with file://

Anyone can suggest something? I'm kinda a noob in iOS programming.

任何人都可以提出建议吗?我是 iOS 编程的菜鸟。

Thanks

谢谢

EDIT: imagePath comes from:

编辑:imagePath 来自:

func getImgPath(name: String) -> String
{
    let documentsDirectory = self.getDocumentsDirectory()
    let fullpath = documentsDirectory.appendingPathComponent(name)
    return fullpath.absoluteString

}

回答by Maulik Bhuptani

This might help

这可能有帮助

let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths             = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath        = paths.first
{
   let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("name.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}

回答by Maulik Bhuptani

Try adding your images under Assets.xcassets. Then you'll be able to reference your image by:

尝试在 下添加您的图像Assets.xcassets。然后,您将能够通过以下方式引用您的图像:

UIImage(named: 'yourImageName')

You can conveniently add images with various size settings.

您可以方便地添加具有各种尺寸设置的图像。

回答by paper1111

You can get the path of the image as fowllows:

你可以得到图像的路径如下:

let imagePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("image.jpg")

If this doesn't work, check if your file name is correct.

如果这不起作用,请检查您的文件名是否正确。

回答by Austin Michael

I understand that if you are downloading images from internet means, you need to convert the URLto UIImage

我了解,如果您从 Internet 下载图像,则需要将其转换URLUIImage

    if let url = URL(string: "your url") {
        let data = try? Data(contentsOf: url)
        if let imageData = data {
            if let image = UIImage(data: imageData) {
                imageView.image = image
            }
        }
    }

If i understand your question correct, this will be the answer.

如果我理解你的问题是正确的,这将是答案。