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

use*_*972 1 base64 image swift

我的 php 代码在服务器上创建了一个空图像

这是我的代码(swift4):

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

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

代码:

$decodimg = base64_decode(_POST["encoded_img"]);
file_put_contents("images/".$imgname,$decodimg);  
Run Code Online (Sandbox Code Playgroud)

以及准备请求的代码:

@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()
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 5

根本问题是您的x-www-form-urlencoded请求格式不正确。您已明确要求它创建包含换行符的 base64 字符串,但x-www-form-urlencoded除非您对它们进行百分比编码,否则不允许使用这些字符串。另外,我们不知道里面有什么样的字符message

我会建议:

  • 除非您确实需要,否则不要要求将换行符添加到 base64 字符串中;但
  • 无论如何,百分比转义字符串值,因为我不知道您对message.

因此:

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()
Run Code Online (Sandbox Code Playgroud)

在哪里

func convertToBase64(image: UIImage) -> String {
    return UIImagePNGRepresentation(image)!
        .base64EncodedString()
}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

或者,您可以考虑使用Alamofire,它可以让您摆脱创建格式良好的x-www-form-urlencoded请求的麻烦