IOS Swift base64 字符串中的 UIImage 到 PHP

IOS Swift UIImage in base64 String to PHP

我正在 Swift 为 Iphone / Ipad 开发应用程序。它是 Android 应用程序的改编版。 问题是: 我有一个调整大小的 UIImage。我想将其转换为字符串以在 PHP 服务器上发送请求。 我已经在 Android

public static String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

返回的字符串被读取并作为图像存储在服务器中用于 PHP 脚本:

$lienphoto = "adressesurleserveur".$nomimage;
$binary=base64_decode($image);
$fichier = fopen($lienphoto, 'wb');
fwrite($fichier, $binary);
fclose($fichier);

我想对swift做同样的事情,我已经试过了:

var imageData = UIImageJPEGRepresentation(imageChoisie, 1.0)
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

和base64String对应的是PHP接收到的String。这不起作用,创建的文件是 "corrupted"。我尝试了几个小时的其他方法,但我还没有解决方案。我发现没有论坛帖子对此问题作出回应。

预先感谢您给我的时间。

我找到了解决办法。

修改在php脚本中:

 $lienphoto = "adresse sur serveur".$nomimage;

$data = str_replace('data:image/jpg;base64,', '', $image);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

$success = file_put_contents($lienphoto, $data);

本站提出的方法:

http://www.tricksofit.com/2014/10/save-base64-encoded-image-to-file-using-php

这保留了 Swift 和 Android 代码。我只需要创建两个 php 脚本来保存图像。