Skip to content

Instantly share code, notes, and snippets.

@brocoo
Last active April 12, 2021 13:27
Show Gist options
  • Save brocoo/6e7466f3138b2e5763ef to your computer and use it in GitHub Desktop.
Save brocoo/6e7466f3138b2e5763ef to your computer and use it in GitHub Desktop.
Swift UIImage extension for base64 conversion
// 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)
}
}
@xeieshan
Copy link

swift 3?

@moshegutman
Copy link

moshegutman commented Mar 20, 2017

I converted the code to Swift 3. I made the string optional since it is possible that converting to jpeg or png may fail. I also made the enumeration cases lowercase, since that's how Apple does it.

public enum ImageFormat {
    case png
    case jpeg(CGFloat)
}

extension UIImage {
    
    public func base64(format: ImageFormat) -> String? {
        var imageData: Data?
        switch format {
        case .png: imageData = UIImagePNGRepresentation(self)
        case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData?.base64EncodedString()
    }
}

@iosdevuz
Copy link

thanks :)

@rogelioesl
Copy link

Very nice ty

@FrancisVimal
Copy link

wonderful thank you

@macbaszii
Copy link

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()
    }
}

@vdhub
Copy link

vdhub commented Jan 22, 2021

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

@LeandroHung
Copy link

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