我正在为Swift开发一个用于Iphone / Ipad的应用程序。它是Android应用程序的改编版。 问题是: 我有一个UIImage我调整了大小。我想将其转换为String以在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;
}
返回的String被读取并作为图像存储在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。这不起作用,创建的文件已损坏"。我尝试了几个小时的其他方法,但我还没有解决方案。我发现没有论坛帖子来回答这个问题。
提前感谢您给予我的时间。
答案 0 :(得分:1)
我找到了解决方案。
修正案是在php脚本中进行的:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
{
NSString *colorAsString = [userDefaults objectForKey:@"color"];
NSArray *components = [colorAsString componentsSeparatedByString:@","];
CGFloat r = [[components objectAtIndex:0] floatValue];
CGFloat g = [[components objectAtIndex:1] floatValue];
CGFloat b = [[components objectAtIndex:2] floatValue];
CGFloat a = [[components objectAtIndex:3] floatValue];
self.view.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:a];
}
该方法在网站上提出:
http://www.tricksofit.com/2014/10/save-base64-encoded-image-to-file-using-php
这保留了Swift和Android代码。我只需创建两个用于保存图像的PHP脚本。