简体   繁体   English

在Swift 4中使用Base64将图像转换为字符串

[英]Image to String using Base64 in swift 4

my php code creates an empty image on server 我的PHP代码在服务器上创建一个空图像

here is my code (swift4) : 这是我的代码(swift4):

var encoded_img = imageTobase64(image: image1.image!)

func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options:   Data.Base64EncodingOptions.lineLength64Characters)
}

php code : PHP代码:

$decodimg = base64_decode(_POST["encoded_img"]);
file_put_contents("images/".$imgname,$decodimg);  

And the code to prepare the request: 以及准备请求的代码:

@IBAction func BtnSend(_ sender: UIButton) {
    var url = "http://xxxxxx/msg.php"
    var encoded_img = imageTobase64(image: image1.image!)    
    let postData = NSMutableData(data: ("message=" + message).data(using: String.Encoding.utf8)!)
    postData.append(("&encoded_img=" + encoded_img).data(using: String.Encoding.utf8)!)    
     request = NSMutableURLRequest(url: NSURL(string: url)! as URL,
 cachePolicy: .useProtocolCachePolicy,
 timeoutInterval: 20.0)
request.httpMethod = "POST"
request.httpBody = postData as Data

let session = URLSession.shared

let dataTask = session.dataTask(with: 
request as URLRequest, completionHandler:

{ (data, response, error)-> Void in
     ...
})

dataTask.resume()

The fundamental issue is that your x-www-form-urlencoded request is not well-formed. 根本问题是您的x-www-form-urlencoded请求x-www-form-urlencoded不正确。 You have explicitly requested it to create base64 string with newline characters in it, but those are not allowed in x-www-form-urlencoded unless you percent encode them. 您已经明确要求它创建带有换行符的base64字符串,但是除非您对它们进行百分比编码,否则x-www-form-urlencoded不允许使用这些字符。 Plus, we don't know what sort of characters are inside message . 另外,我们不知道message哪种字符。

I would suggest: 我会建议:

  • Not request newline characters to be added to the base64 string unless you really needed them; 除非您确实需要换行符,否则请不要将它们添加到base64字符串中。 but
  • Percent escape the string values, anyway, as I don't know what sort of values you have for message . 无论如何,百分比都会转义字符串值,因为我不知道message具有什么样的值。

Thus: 从而:

let parameters = [
    "message": message,
    "encoded_img": convertToBase64(image: image1.image!)
]

let session = URLSession.shared

let url = URL(string: "http://xxxxxx/msg.php")!
var request = URLRequest(url: url, timeoutInterval: 20.0)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  // not necessary, but best practice
request.setValue("application/json", forHTTPHeaderField: "Accept")                         // again, not necessary, but best practice; set this to whatever format you're expecting the response to be

request.httpBody = parameters.map { key, value in
    let keyString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
    let valueString = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
    return keyString + "=" + valueString
    }.joined(separator: "&").data(using: .utf8)


let dataTask = session.dataTask(with:request) { data, response, error  in
    guard error == nil,
        let data = data,
        let httpResponse = response as? HTTPURLResponse,
        (200 ..< 300) ~= httpResponse.statusCode else {
            print(error ?? "Unknown error", response ?? "Unknown response")
            return
    }

    // process `data` here
}

dataTask.resume()

where 哪里

func convertToBase64(image: UIImage) -> String {
    return UIImagePNGRepresentation(image)!
        .base64EncodedString()
}

and

extension CharacterSet {

    /// Character set containing characters allowed in query value as outlined in RFC 3986.
    ///
    /// RFC 3986 states that the following characters are "reserved" characters.
    ///
    /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
    /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
    ///
    /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
    /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
    /// should be percent-escaped in the query string.
    ///
    /// - parameter string: The string to be percent-escaped.
    ///
    /// - returns: The percent-escaped string.

    static var urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return allowed
    }()

}

Alternatively, you could consider using Alamofire which gets you out of the weeds of creating well-formed x-www-form-urlencoded requests. 另外,您可以考虑使用Alamofire ,它使您摆脱了创建格式正确的x-www-form-urlencoded请求x-www-form-urlencoded

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM