我正在尝试将iOS设备上的图片文件上传到远程SQL Server的VARBINARY(MAX)列,但遇到了困难。
基本上我需要将UIImage转换为我需要插入的内容:
INSERT INTO table (ImageColumn) VALUES ('byteString here')
列类型是:VARBINARY(MAX),我可以通过以下方式打印字符串:
let imageData = UIImagePNGRepresentation(value)
let base64String = imageData?.base64EncodedString()
imageBase64 = base64String!
print(imageBase64) // this prints all the string
这甚至会将8-9mb的数据写入列,但它总是被破坏。我不知道我的sql查询字符串是否完全错误
编辑:快速修复
let value_resized = value.resizedTo1MB()
let imageData = UIImageJPEGRepresentation(value_resized!, 0)
let strBase64 = imageData?.base64EncodedString(options: .lineLength64Characters)
imageBase64 = strBase64!
// i can insert imageBase64 to sql as a string
extension UIImage {
func resized(withPercentage percentage: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resizedTo1MB() -> UIImage? {
guard let imageData = UIImagePNGRepresentation(self) else { return nil }
var resizingImage = self
var imageSizeKB = Double(imageData.count) / 1000.0
while imageSizeKB > 1000 {
guard let resizedImage = resizingImage.resized(withPercentage: 0.9),
let imageData = UIImagePNGRepresentation(resizedImage)
else { return nil }
resizingImage = resizedImage
imageSizeKB = Double(imageData.count) / 1000.0
}
return resizingImage
}
}