我有一个自定义的应用内构建相机。该相机可以拍摄照片和视频,然后将照片保存到用户库中。我现在想在将图片制作到图像时添加 iPhone 中的当前位置。 我发现了这个:
func addLocationToImage(image: UIImage, location: CLLocation) throws -> UIImage {
guard let data = image.jpegData(compressionQuality: 1.0) else {
throw NSError(domain: "error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to get JPEG data from image."])
}
let metadata = NSMutableDictionary()
let gpsDict = NSMutableDictionary()
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
gpsDict[(kCGImagePropertyGPSLatitude as String)] = abs(latitude)
gpsDict[(kCGImagePropertyGPSLatitudeRef as String)] = latitude < 0.0 ? "S" : "N"
gpsDict[(kCGImagePropertyGPSLongitude as String)] = abs(longitude)
gpsDict[(kCGImagePropertyGPSLongitudeRef as String)] = longitude < 0.0 ? "W" : "E"
metadata[(kCGImagePropertyGPSDictionary as String)] = gpsDict
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
throw NSError(domain: "error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to create image source from data."])
}
let uti = CGImageSourceGetType(source)!
let mutableData = NSMutableData(data: data)
guard let destination = CGImageDestinationCreateWithData(mutableData, uti, 1, nil) else {
throw NSError(domain: "error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to create image destination."])
}
CGImageDestinationAddImageFromSource(destination, source, 0, metadata)
guard CGImageDestinationFinalize(destination) else {
throw NSError(domain: "error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to write image with metadata to data."])
}
guard let imageWithGPSData = UIImage(data: mutableData as Data) else {
throw NSError(domain: "error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to create image from data with GPS metadata."])
}
return imageWithGPSData
}
但这似乎不起作用。 我是否做错了什么,因为位置在那里,但它没有添加到图像中。
UIImage
没有任何元数据。一旦您从更新的数据(带有添加的 GPS 信息)返回到 UIImage
,该元数据就会丢失。
更新您的方法以返回更新后的
Data
(mutableData
) 而不是 UIImage
。然后,您可以根据需要保留该数据,以便与新的元数据一起保存。
这是最简单的方法我发现在将图像保存到用户的照片库(照片应用程序)之前设置图像的位置。
创建新
PHAssetCreationRequest
时,可以直接将位置添加到PHAssetCreationRequest
,如下所示:
// get the user's location in whatever way you like
let location = CLLocation(latitude: 7.2906, longitude: 80.6337)
let creationRequest = PHAssetCreationRequest.forAsset()
// add location data
creationRequest.location = location
就是这样。现在,当您保存图像数据时,这些位置数据也会添加到图像中。