Convert between UIImage and Base64 string

后端 未结 24 2547
抹茶落季
抹茶落季 2020-11-22 01:45

Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?

I have the below code; the original image before encoding is good, bu

24条回答
  •  终归单人心
    2020-11-22 01:57

    See my class -  AppExtension.swift
    
    
    // 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)
        }
    }
    

提交回复
热议问题