gpt4 book ai didi

ios - Postgres + Perfect + Swift 将 UIImage 上传为 Base64

转载 作者:行者123 更新时间:2023-11-28 06:19:43 25 4
gpt4 key购买 nike

我所要做的就是让用户选择照片,将其上传到服务器,然后解码并显示出来。我现在正在做的是对图像进行编码,然后将其作为 Base64 传递给模型。我将它作为 bytea 存储在 PosgtgreSQL 中。

let imageb: NSData = UIImageJPEGRepresentation(image, 0.7)! as NSData
let dataDecoded: String = imageb.base64EncodedString(options: .lineLength64Characters)
let imageStr: String = dataDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

然后在我的模型中有

private var JSON: [String: Any] {
get {
return ["data": self.imageData]
}
}

然后我使用Alamofire将它发布到服务器上

APILayer.shared.request(parameters: self.JSON, url: "photo/create", method: .post) { responce in
//some handling stuff
}

服务器端客户端网关方式

let photos = user.getPhotos()
try! response.setBody(json: PhotoDocument.jsonFrom(array: photos))

对象方法

func getPhotos() -> [PhotoDocument] {
return PhotoDocumentMapper.search(id: self.id)
}

private var JSON: [String: Any] {
get {
return ["description": self.description, "importancy": self.importancy, "date": self.date, "data": self.imageData, "id": self.id]
}
}

class func jsonFrom(array: [PhotoDocument]) -> [String: Any] {
var jsons: [Any] = []

for photo in array {
jsons.append(photo.JSON)
}

return ["photos" : jsons]
}

数据映射器方法

class func search(id: Int) -> [PhotoDocument] {
let p = PGConnection()
let _ = p.connectdb("host=localhost port=5432 dbname=perfect")
let result = p.exec(statement: "select * from \"Photos\" where \"userId\" = $1", params: [id])
p.close()
var photos: [PhotoDocument] = []
let resultsNumber = result.numTuples() - 1
if resultsNumber != -1 {
for index in 0...resultsNumber {
let id = result.getFieldInt(tupleIndex: index, fieldIndex: 0)!
let description = result.getFieldString(tupleIndex: index, fieldIndex: 4)!
let date = result.getFieldString(tupleIndex: index, fieldIndex: 5)!
let imageData = result.getFieldString(tupleIndex: index, fieldIndex: 3)!
let importancy = result.getFieldInt(tupleIndex: index, fieldIndex: 2)!
let userId = result.getFieldInt(tupleIndex: index, fieldIndex: 1)!

let photo = PhotoDocument(userId: userId, description: description, date: date, id: id, imageData: imageData, importancy: importancy)
photos.append(photo)
}
}
return photos
}

然后我收到所有这些数据,我收到巨大的 String 并尝试这个,但它在第一行崩溃

let dataDecoded: NSData = NSData(base64Encoded: photo.imageData, options: .ignoreUnknownCharacters)! //crash here
let decodedimage = UIImage(data: dataDecoded as Data)
self.test.image = decodedimage

我做错了什么?如何将 UIImage 存储为 Base64String 作为 PostgreSQLbytea

最佳答案

所以我要做的就是在编码时删除这一行

let imageStr: String = dataDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

并将 PostgreSQL 字段更改为 text 而不是 bytea

关于ios - Postgres + Perfect + Swift 将 UIImage 上传为 Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009775/

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