Swift-将base64编码的图像上传到php并显示该图像 [英] Swift - uploading base64 encoded image to php and displaying the image

查看:124
本文介绍了Swift-将base64编码的图像上传到php并显示该图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently, I'm trying to upload a base64 encoded image to a php server which is then storing the base64 string in a MySQL database. Currently, the code is uploading the data and storing it into the MySQL database. However, when I attempt to retrieve the image by specifying the URL used to retrieve the image, a missing image link with the question mark is shown. I have no idea why this is happening since both uploading and displaying base64 encoded images seems to be working just fine with my Android app.

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

Here is the Swift code I'm using to encode and upload to the server:

    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

这是将base64字符串解码并显示在浏览器中的PHP代码.这对于我的Android代码上传的图像效果很好,但它仅显示了我的Swift代码上传的图像的损坏的图像链接.

Here is the PHP code where the base64 string is being decoded and displayed in the browser. This is working fine for images that are uploaded by my Android code, but it just shows a broken image link for images uploaded by my Swift code.

 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字符串发布到PHP服务器之前对它进行百分比编码来使其正常工作.希望这对其他人有帮助.

I was able to get this working by percent encoding the base64 string before posting it to the PHP server. Hope this helps someone else.

这篇关于Swift-将base64编码的图像上传到php并显示该图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆