簡體   English   中英

使用Swift 3將圖像轉換為base64時出現問題

[英]Issues converting image to base64 with Swift 3

我正在嘗試將圖像上傳到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
--------------------------------

如果您希望JSON作為application/json返回,請確保標頭包含Content-TypeAccept

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
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 ..,也可以按比例縮放或等於。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM