简体   繁体   中英

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

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.

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

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"]     . '" />';
     }

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.

Just supplying some helpful Swift 3.0 code here on the back of play2win's self-answer:

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

你应该首先将你的base64图像解码为数据并保存在服务器端,这样我们就可以获得你所希望的响应的保存位置路径。希望这有助于你......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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