简体   繁体   English

如何从 UIImage 获取 URL

[英]How to get URL from UIImage

How can I get an URL from UIImage?如何从 UIImage 获取 URL? I've got an image from iPhone library and I resize it and I don't want to save the new image but I want to get it's URL.我从 iPhone 库中获得了一个图像,我调整了它的大小,我不想保存新图像,但我想获取它的 URL。

You say you don't want to save it, but if you need a URL for a UIImage , you can easily save a temp copy to get the URL that you need.您说您不想保存它,但是如果您需要UIImage的 URL,您可以轻松保存临时副本以获取您需要的 URL。

For newer swift 5:对于较新的 swift 5:

// Create a URL in the /tmp directory
guard let imageURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempImage.png") else {
    return
}

let pngData = image.pngData();
do {
    try pngData?.write(to: imageURL);
} catch { }

Now you can use the URL to share the image to social media or whatever you need to do with it.现在,您可以使用 URL 将图像分享到社交媒体或您需要对其进行的任何操作。

For previous Swift versions:对于以前的 Swift 版本:

// Create a URL in the /tmp directory
guard let imageURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempImage.png") else {
    return
}

// save image to URL
do {
    try UIImagePNGRepresentation(myImage)?.write(to: imageURL)
} catch { }

See here for more.请参阅此处了解更多信息。

UIImage has no URL or file information. UIImage 没有 URL 或文件信息。 It's just a collection of bytes representing the pixel color data.它只是代表像素颜色数据的字节集合。 If you get the UIImage from a UIImagePicker then you can get the URL to the original image in the asset library.如果您从 UIImagePicker 获取 UIImage,则可以获取资源库中原始图像的 URL。 But you must get this URL in the image picker delegate method and you must keep track of it separately from the UIImage object.但是您必须在图像选择器委托方法中获取此 URL,并且必须与 UIImage 对象分开跟踪它。

Edit - based on the OP's comment, this is not the information being requested.编辑 - 根据 OP 的评论,这不是所请求的信息。

What you are looking for is the UIImagePickerControllerReferenceURL parameter provided by the delegate callback in the info dictionary.您正在寻找的是信息字典中委托回调提供的UIImagePickerControllerReferenceURL参数。 What you need to do is:你需要做的是:

NSURL* imageURL = [info objectForKey:UIImagePickerControllerReferenceURL];

And it would look something like this:它看起来像这样:

assets-library://asset/asset.JPG?id=SOME_GUUID&ext=JPG

You could use this latter to refer back to the same image you got in the UIImage* in the callback.您可以使用后者来引用您在回调中的UIImage*中获得的相同图像。

You could subclass UIImage and create an override initWithURL: to save the URL to a created property... something like this.您可以继承 UIImage 并创建一个覆盖 initWithURL: 以将 URL 保存到创建的属性......像这样。

+ (id) initWithURL:(NSURL*)url
{
    [super initWithURL:url];
    self.url = url;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM