gpt4 book ai didi

ios - 使用 Imagga API 和 Alamofire

转载 作者:行者123 更新时间:2023-11-30 12:11:57 25 4
gpt4 key购买 nike

我试图将图像上传到 IMAGGA API 并为我的项目取回一些图像识别标签,但我无法获取所需的标签。我已经使用 Alamofire 上传图像,但我收到此错误,并且 API 调用中没有标签。

这是我用来上传图像的函数。代码:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
defer {
picker.dismiss(animated: true)
}

print(info)
// get the image
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
return
}

imageView.image = image


let documentDirectory: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString

let imageName = "temp"
let imagePath = documentDirectory.appendingPathComponent(imageName)

if let data = UIImageJPEGRepresentation(image, 80) {
// Save cloned image into document directory
let urlFile = NSURL(string: imagePath)

do {
try data.write(to: urlFile! as URL, options: .atomic)
} catch {
print(error)
}
// Save it's path
localPath = imagePath
}

let imageData = UIImagePNGRepresentation(image)!

//

let headers: HTTPHeaders = [
"Authorization": "Basic YWNjX2MwNDUzYzkzNTEyOGNkYzo0ZmE5MWM4Zjg0MDk1ZGI0NGE2ZjNjODJkNTczZDUxOQ==",
"Accept": "application/json"
]

Alamofire.request("https://httpbin.org/basic-auth/\("acc_c0453c935128cdc")/\("4fa91c8f84095db44a6f3c82d573d519")", parameters: ["url": "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg"], headers: headers)
.authenticate(user: "acc_c0453c935128cdc", password: "4fa91c8f84095db44a6f3c82d573d519")
.responseJSON { response in
debugPrint(response)
switch(response.result) {
case .success(_):
if let data = response.result.value{


print("YOUR JSON DATA>> \(response.data!)")


}
break

case .failure(_):
print(response.result.error)


break

}

}



}

我收到此错误。最后显示成功,但我不确定图像是否发送到 imagga 进行图像识别。

Error:

URL which has no scheme
Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/var/mobile/Containers/Data/Application/D8A0EE1D-2092-474F-B21A-8A7E0635AD40/Documents/temp}
[Request]: GET https://httpbin.org/basic-auth/acc_c0453c935128cdc/4fa91c8f84095db44a6f3c82d573d519?url=http%3A//docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg
[Response]: <NSHTTPURLResponse: 0x1702210e0> { URL: https://httpbin.org/basic-auth/acc_c0453c935128cdc/4fa91c8f84095db44a6f3c82d573d519?url=http%3A//docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg } { status code: 200, headers {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 62;
"Content-Type" = "application/json";
Date = "Tue, 29 Aug 2017 16:42:07 GMT";
Server = "meinheld/0.6.1";
Via = "1.1 vegur";
"X-Powered-By" = Flask;
"X-Processed-Time" = "0.000633001327515";
} }
[Data]: 62 bytes
[Result]: SUCCESS: {
authenticated = 1;
user = "acc_c0453c935128cdc";
}
[Timeline]: Timeline: { "Request Start Time": 525717726.320, "Initial Response Time": 525717728.876, "Request Completed Time": 525717728.882, "Serialization Completed Time": 525717728.889, "Latency": 2.556 secs, "Request Duration": 2.562 secs, "Serialization Duration": 0.006 secs, "Total Duration": 2.569 secs }
YOUR JSON DATA>> 62 bytes

最佳答案

可能是因为您的参数编码不正确。您的问题提到了 Imagga,但您正在使用 httpbin 进行调试。

这是 Alamofire + Imagga 的 API 的工作示例:

使用远程图像

    let parameters: Parameters = [
"version" : 2,
"url" : "http://playground.imagga.com/static/img/example_photo.jpg"
]
var headers: HTTPHeaders = [
"Accept" : "application/json"
]

// Three ways to add the auth header (3rd is to use authenticate method):
// 1. Append the basic encoded value already provided by Imagga's dashboard
// headers["Authorization"] = "Basic xxxxxx=="
// 2. Construct the header using the api key + api secret
if let authorizationHeader = Request.authorizationHeader(user: "api_ley", password: "api_secret") {
headers[authorizationHeader.key] = authorizationHeader.value
}

Alamofire
.request("http://api.imagga.com/v1/tagging", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON { (response) in
print(response)
}

回应:

{
"results": [
{
"tagging_id": null,
"image": "http://playground.imagga.com/static/img/example_photo.jpg",
"tags": [
{
"confidence": 71.4296152834829,
"tag": "beach"
},
{
"confidence": 52.843097989562466,
"tag": "sea"
},
{
"confidence": 46.13550857065488,
"tag": "sun"
},
{
"confidence": 43.923454585374714,
"tag": "ocean"
},
{
"confidence": 43.23227098537762,
"tag": "water"
},
{
"confidence": 7.113114870093362,
"tag": "leisure"
}
]
}
]
}
<小时/>

上传本 map 片

正如文档中提到的,您需要首先将图像上传到 content 端点。

简单的响应结构使 JSON 解析更容易(Swift 4。使用 Swift 3 应该很容易,但更乏味):

struct ImaggaContentResponse: Decodable {
let status: String
let message: String?
let uploaded: [ImaggaContent]

struct ImaggaContent: Decodable {
let id, filename: String
}
}


/// Represents the available sources for images
///
/// - url: Represents a remote images (URL must be specified)
/// - content: Represents a previously uploaded local image to the content endpoint (content id must be provided)
enum ImaggaImageOrigin {
case url(String)
case content(String)
}


示例:

class ViewController: UIViewController {

var headers: HTTPHeaders = {
var defaultheaders = [
"Accept" : "application/json"
]
if let authorizationHeader = Request.authorizationHeader(user: "api_key", password: "api_secret") {
defaultheaders[authorizationHeader.key] = authorizationHeader.value
}

return defaultheaders
}()

override func viewDidLoad() {
super.viewDidLoad()

let imageData = UIImage.make(from: .purple).jpeg!
Alamofire.upload(
multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
},
to: "https://api.imagga.com/v1/content",
method: .post,
headers: headers,
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print(progress)
})
upload.responseData { response in
guard let jsonData = response.value,
let contentResponse = try? JSONDecoder().decode(ImaggaContentResponse.self, from: jsonData)
else { return }

let firstImage = contentResponse.uploaded.first!
self.tagImage(from: .content(firstImage.id))
}
case .failure(let encodingError):
print (encodingError)
}
})
}

func tagImage(from source: ImaggaImageOrigin) {
var parameters: Parameters = [
"version" : 2,
]

switch source {
case .url(let imageUrl):
parameters["url"] = imageUrl
case .content(let contentId):
parameters["content"] = contentId
}

Alamofire
.request("http://api.imagga.com/v1/tagging", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseString { (response) in
print(response)
}
}
}

关于ios - 使用 Imagga API 和 Alamofire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944453/

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