gpt4 book ai didi

swift - 将图像从 firebase 存储传输到 firebase 数据库

转载 作者:可可西里 更新时间:2023-11-01 02:05:42 26 4
gpt4 key购买 nike

我在我的 firebase 存储中为每个用户存储了一张个人资料图片。这是引用:

profilePicRef = FIRStorage.storage().reference().child((FIRAuth.auth()?.currentUser.uid)!+"/profile_pic.jpg")

我希望能够从我的存储中访问图片并使用此路径将其放入我的数据库中:

@IBAction func Post(_ sender: AnyObject) {

let postObject: Dictionary<String, Any> = [

"userpic" : ""
]

FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).childByAutoId().setValue(postObject)

}

我不清楚“userpic”旁边的引号中包含什么内容

最佳答案

数据库本身并不适合存储照片(但是从技术上讲,您可以执行 base64 encoding of an image ,如果图像非常小,这可能会更好)。

我发现最适合个人资料图像的方法是根据 UID 将它们存储在 Firebase 存储中。当我想上传图片时,我先调整它的大小:

// from https://stackoverflow.com/a/29138120/1822214.  Only for square images.
func resizeWith(_ width: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}

然后我像这样上传它:

    func uploadProfilePic(_ uid: String, image: UIImage?, completion: @escaping (Bool) -> ())
// compress with moderate quality (between 0 and 1)
let data: Data = UIImageJPEGRepresentation(image!, 0.5)!
let profileRef = storageRef.child("users/\(uid)/profile.jpg")

let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpg"

// Upload the file
let uploadTask = profileRef.put(data, metadata: metadata) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
print("there was an error uploading the profile pic!")
print(error)
// completion with failure... :(
completion(false)
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
// completion with success!
completion?(true)
}
}
}

我希望这可以帮助您入门,如果您有任何问题,请告诉我。

关于swift - 将图像从 firebase 存储传输到 firebase 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com