Swift - 上传base64编码图片到php并显示图片

Swift - uploading base64 encoded image to php and displaying the image

目前,我正在尝试将 base64 编码的图像上传到 php 服务器,然后服务器将 base64 字符串存储在 MySQL 数据库中。目前,代码正在上传数据并将其存储到 MySQL 数据库中。但是,当我尝试通过指定用于检索图像的 URL 来检索图像时,会显示带有问号的缺失图像 link。我不知道为什么会发生这种情况,因为上传和显示 base64 编码图像似乎都可以在我的 Android 应用程序中正常工作。

这是我用来编码并上传到服务器的 Swift 代码:

    let image: UIImage = imgProfilePic.image!

    let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.3, 0.3))
    let hasAlpha = false
    let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

    UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
    image.drawInRect(CGRect(origin: CGPointZero, size: size))

    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    var imageData = UIImageJPEGRepresentation(scaledImage, 0.9)
    var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image

    var cd = CoreDataUser(pstrContext: "this")

    var params = "strUsername=" + cd.getUsername()
    params = params + "&strPassword=" + cd.getPassword()
    params = params + "&blbProfilePic=" + base64String

这里是 PHP 代码,其中 base64 字符串被解码并显示在浏览器中。这对于由我的 Android 代码上传的图像来说工作正常,但对于由我的 Swift 代码上传的图像,它只显示损坏的图像 link。

 if ($rows) { 
    foreach ($rows as $row) { 
    $data = base64_decode($row["fblbProfilePic"]);
    $image = imagecreatefromstring($data);
    header('Content-Type: Image/jpeg');
    imagejpeg($image);
//file_put_contents("test.jpg", $data);
//var_dump($data);

    //echo base64_decode($row["fblbPicture"]);
    /    /echo '<img src="data:image/jpg;base64,' . $row["fblbPicture"]     . '" />';
     }

您应该首先将您的 base64 图像解码为数据并保存在服务器端,以便我们将获得您保存的位置路径作为您想要的响应.. 希望这对你有帮助...

我能够通过在将 base64 字符串发布到 PHP 服务器之前对 base64 字符串进行百分比编码来使其正常工作。希望这对其他人有帮助。

只是在 play2win 的自我回答后面提供一些有用的 Swift 3.0 代码:

let data:Data = UIImagePNGRepresentation(myUIImageView.image!)!
let base64String:String = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
let imageStr:String = base64String.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!