目前,我正在尝试将 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
这是 base64 字符串被解码并显示在浏览器中的 PHP 代码。这对于由我的 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 字符串进行百分比编码来实现它。希望这对其他人有帮助。
关于php - Swift - 将base64编码的图片上传到php并显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29581333/