【问题标题】:Issues converting image to base64 with Swift 3使用 Swift 3 将图像转换为 base64 的问题
【发布时间】:2018-05-02 12:17:39
【问题描述】:

我正在尝试将图像上传到 imgur,并希望获得图像的 url。 Imgur 要求传入的图像是二进制文件、base64 数据或图像的 URL。我正在将图像转换为 base64 并收到一条错误消息,指出它是无效的文件类型。

这是我的代码:

  let imageData = UIImagePNGRepresentation(checkView.image!)
    let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)

    let urlPath = "https://api.imgur.com/3/upload"
    let url = URL(string:urlPath)

    var request = URLRequest(url: url!)
    request.setValue("Client-ID MyClientIDKEy", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"

    // create post string with username and password
    let postString = "image=" + base64Image!
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            // check for fundamental networking error
            print("Data empty or error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 405 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response from status code = \(String(describing: response))")
        }

        // store data
        let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
        let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

        // printing feedback
        print("responseString = \(responseString)")
        print("--------------------------------")
        print(json)
        print("--------------------------------")

    }
    task.resume()
}

以及我得到的回应:

statusCode should be 200, but is 415
response from status code = Optional(<NSHTTPURLResponse: 0x1c0225280> { URL: https://api.imgur.com/3/upload } { Status Code: 415, Headers {
"Access-Control-Allow-Origin" =     (
    "*"
);
"Cache-Control" =     (
    "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
);
"Content-Length" =     (
    174
);
"Content-Type" =     (
    "application/json"
);
Date =     (
    "Sat, 18 Nov 2017 23:14:27 GMT"
);
Server =     (
    nginx
);
"access-control-allow-headers" =     (
    "Authorization, Content-Type, Accept, X-Mashape-Authorization, IMGURPLATFORM, IMGURUIDJAFO, SESSIONCOUNT, IMGURMWBETA, IMGURMWBETAOPTIN"
);
"access-control-allow-methods" =     (
    "GET, PUT, POST, DELETE, OPTIONS"
);
"access-control-expose-headers" =     (
    "X-RateLimit-ClientLimit, X-RateLimit-ClientRemaining, X-RateLimit-UserLimit, X-RateLimit-UserRemaining, X-RateLimit-UserReset"
);
"x-post-rate-limit-limit" =     (
    1250
);
"x-post-rate-limit-remaining" =     (
    1246
);
"x-post-rate-limit-reset" =     (
    3039
);
} })

 responseString = Optional({"data":{"error":{"code":1003,"message":"File type invalid (2)","type":"ImgurException","exception":{}},"request":"\/3\/upload","method":"POST"},"success":false,"status":415})

Optional(["status": 415, "data": {
    error =     {
        code = 1003;
        exception =         {
        };
        message = "File type invalid (2)";
        type = ImgurException;
    };
    method = POST;
    request = "/3/upload";
}, "success": 0])

--------------------------------
nil
--------------------------------

【问题讨论】:

  • 我遇到了同样的问题,但以下答案都没有解决问题。

标签: ios swift api imgur


【解决方案1】:
extension UIImage{
    public func toBase64() -> String{
        let imageData = UIImageJPEGRepresentation(self, 1.0)
        return (imageData?.base64EncodedString())!
    }

    public func scaleTo(ratio: CGFloat) -> UIImage {
        let size = self.size
        let newSize: CGSize = CGSize(width: size.width  * ratio, height: size.height * ratio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

    public func isEqualToImage(image: UIImage) -> Bool {
        let data1 = UIImagePNGRepresentation(self)
        let data2 = UIImagePNGRepresentation(image)
        return data1 == data2
    }
}

在此扩展程序中,您可以选择 Base64.. 或者您可以按比例缩放或等于。

【讨论】:

    【解决方案2】:

    如果您希望 JSON 返回为 application/json,请确保您的标头包含 Content-TypeAccept

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      相关资源
      最近更新 更多