簡體   English   中英

從MySQL收到的Swift中將base64字符串編碼為圖像

[英]Encoding base64 string to image in swift received from mysql

我從mysql接收到base64字符串(存儲為blob),並嘗試將其編碼為:

func loadImage() {
    var request = URLRequest(url: URL(string: URL_IMAGES)!)
    request.httpMethod = "POST"
    let userid = self.defaultValues.integer(forKey: "userid")
    let postString = "userid=\(userid)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        if let encodedImage = responseString,
            let imageData =  NSData(base64Encoded: encodedImage, options: .ignoreUnknownCharacters),
            let image = UIImage(data: imageData as Data) {
            print(image.size)
        }
    }
    task.resume()
}

php文件如下所示:

<?php
$userid=$_POST["userid"];
$conn = mysqli_connect(connection);
if ($conn->connect_error) {
    die("Connection failed: " . $conn>connect_error);
} 
$sql = "SELECT profilepicture FROM users WHERE id = $userid";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     while($row = $result->fetch_assoc()) {
         $out[]=$row;
     }
    echo json_encode($out);
} else {
  echo "0 results";
}
?>

編輯2 *這就是我將圖像存儲到數據庫中的方式:

@objc func updateUser(sender: UIButton!) {
    let refreshAlert = UIAlertController(title: "Update profile?", message: "Do you want to update your profile? This will log you out to update the data!", preferredStyle: UIAlertControllerStyle.alert)
    refreshAlert.view.tintColor = UIColor.red
    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in

        let URL_REQUEST = "request"

        self.messageLbl.text = ""

        var request = URLRequest(url: URL(string: URL_REQUEST)!)
        request.httpMethod = "POST"
        let userid = self.defaultValues.integer(forKey: "userid")
        let password = self.passWordTf.text!
        let email = self.eMailTf.text!
        let image = self.imageView.image!
        guard let pictStr = self.convertImageBase64(image: image) else {
            return
        }
        let postString = "id=\(userid)&password=\(password)&email=\(email)&profilepicture=\(pictStr)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()

        if (self.eMailTf.text != self.defaultValues.string(forKey: "useremail")) {
            self.defaultValues.set(self.eMailTf.text, forKey: "useremail")
        }
        self.navigationController?.popViewController(animated: true)
    }))

    refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in
        print("Handle Cancel Logic here")
    }))

    present(refreshAlert, animated: true, completion: nil)
}

編輯2 *這是編碼功能:

func convertImageBase64(image: UIImage) -> String? {
    guard let pictData = UIImagePNGRepresentation(image) else {
        return nil
    }
    let strBase64: String = pictData.base64EncodedString(options: [])
    return strBase64
}

編輯2 *和用於存儲的php文件:

<?php
$userid=$_POST["userid"];
$password=$_POST["password"];
$pass = md5($password);
$email=$_POST["email"];
$profilepicture=$_POST["profilepicture"];


$conn = mysqli_connect(connection);

if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 

$sql =("UPDATE users SET password='".$pass."' ,  email='".$email."' , profilepicture='".$profilepicture."' WHERE id=".$userid."");

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

這是一個類似的問題這個 ,但即使嘗試所有的答案並沒有為我工作。 我得到的響應是正確的,但我無法對其進行編碼,因為我總是在嘗試編碼時得到nil:

我也嘗試過很多類似的事情:

在Swift中從JSON解碼base64_encode圖像

編輯1

im接收的字符串具有以下前綴:“ [{\\” profilepicture \\“:\\” iVBORw0KGgoAAAANSUhE ...

是否可以在沒有此前綴的情況下轉換字符串,或者該前綴甚至與轉換字符串都不相關?

編輯2

您的服務器端代碼返回JSON數據,其中包含通過fetch_assoc()檢索的assoc數組的數組。

我建議您更新服務器端代碼,因為它返回除圖像數據以外的其他內容,因此最好只發送圖像數據。

但是,如果您想按原樣使用服務器端代碼,則可能需要在loadImage編寫如下loadImage

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error?.localizedDescription ?? "nil")")
            return
        }

        guard let httpResponse = response as? HTTPURLResponse else {
            print("response is not an HTTPURLResponse")
            return
        }
        guard httpResponse.statusCode == 200 else {
            print("statusCode should be 200, but is \(httpResponse.statusCode)")
            print("response = \(httpResponse)")
            return
        }

        do {
            //First decode the response body as JSON
            let json = try JSONSerialization.jsonObject(with: data)
            //The decoded object should be a JSON array containing one JSON object
            guard let arr = json as? [[String: Any]], !arr.isEmpty else {
                print("json is not an array, or is empty")
                return
            }
            //Use only the first record
            let person = arr[0]
            //Retrieve the column value of "profilepicture" in the first record
            guard let encodedImage = person["profilepicture"] as? String else {
                print("NO profilepicture")
                return
            }
            //Decode it into binary data as Base64
            guard let imageData =  Data(base64Encoded: encodedImage, options: .ignoreUnknownCharacters) else {
                print("encodedImage is not a valid Base64")
                return
            }
            //Convert the decoded binary data into an image
            guard let image = UIImage(data: imageData) else {
                print("imageData is in a unsupported format or is not an image")
                return
            }
            print(image.size)
            //Use `image` here...
        } catch {
            print(error)
        }
    }
    task.resume()

您可能需要修改某些部分,但是當我在壞情況下嵌入許多print ,可以輕松找到要修復的地方。

暫無
暫無

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

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