使用Swift 3将图像转换为base64的问题

时间:2017-11-18 23:54:43

标签: ios swift api imgur

我正在尝试将图片上传到imgur并希望获得图片的网址。 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
--------------------------------

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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
    }
}

在此扩展程序中,您有选项toBase64 ..或者您可以缩放到比率,或等于。