Last active
April 12, 2021 13:27
-
-
Save brocoo/6e7466f3138b2e5763ef to your computer and use it in GitHub Desktop.
Swift UIImage extension for base64 conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: - UIImage (Base64 Encoding) | |
public enum ImageFormat { | |
case PNG | |
case JPEG(CGFloat) | |
} | |
extension UIImage { | |
public func base64(format: ImageFormat) -> String { | |
var imageData: NSData | |
switch format { | |
case .PNG: imageData = UIImagePNGRepresentation(self) | |
case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression) | |
} | |
return imageData.base64EncodedStringWithOptions(.allZeros) | |
} | |
} |
wonderful thank you
For who looking for Swift 4.2 version
public enum ImageFormat {
case png
case jpeg(CGFloat)
}
extension UIImage {
public func toBase64(format: ImageFormat) -> String? {
var imageData: Data?
switch format {
case .png:
imageData = self.pngData()
case .jpeg(let compression):
imageData = self.jpegData(compressionQuality: compression)
}
return imageData?.base64EncodedString()
}
}
Is it possible to have this in the latest swift and Xcode I guess 12.3 for me but for macOS not for iOS , as no matter where I search I always find code for iOS only with the UIImage and macOS has NSImage . In my case I need to get the image from a Image View and save it as base64
Thanks in advance
enum ImageFormat
{
case png
case jpeg(CGFloat)
}
extension UIImage
{
func image2String64(_ format: ImageFormat) -> String?
{
var imageData: Data?
switch format
{
case .png:
imageData = UIImagePNGRepresentation(self)
case .jpeg(let compression):
imageData = UIImageJPEGRepresentation(self, compression)
}
return imageData?.base64EncodedString()
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice ty