目前,我正在尝试将 base64 编码的图像上传到 php 服务器,然后该服务器将 base64 字符串存储在 MySQL 数据库中。目前,代码正在上传数据并将其存储到MySQL数据库中。但是,当我尝试通过指定用于检索图像的 URL 来检索图像时,会显示带有问号的缺失图像链接。我不知道为什么会发生这种情况,因为上传和显示 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 代码上传的图像的损坏的图像链接。
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"] . '" />';
}
在将其发布到 PHP 服务器之前,我能够通过对 Base64 字符串进行百分比编码来实现此功能。希望这对其他人有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)