Convert between UIImage and Base64 string
Swift
First we need to have image's NSData
//Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
//OR next possibility
//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!
Swift 2.0 > Encoding
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Swift 2.0 > Decoding
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
Swift 3.0 > Decoding
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
Encoding :
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)
Decoding :
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage
Swift 3.0
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage
Objective-C
iOS7 > version
You can use NSData's
base64EncodedStringWithOptions
Encoding :
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
Decoding :
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
iOS 6.1 and < version
First Option : Use this link to encode
and decode
image
Add Base64 class in your project
.
Encoding :
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
NSString *strEncoded = [Base64 encode:data];
Decoding :
NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];
Another Option: Use QSUtilities for encoding
and decoding
Image to String using Base64 in swift 4
The fundamental issue is that your x-www-form-urlencoded
request is not well-formed. You have explicitly requested it to create base64 string with newline characters in it, but those are not allowed in x-www-form-urlencoded
unless you percent encode them. Plus, we don't know what sort of characters are inside message
.
I would suggest:
- Not request newline characters to be added to the base64 string unless you really needed them; but
- Percent escape the string values, anyway, as I don't know what sort of values you have for
message
.
Thus:
let parameters = [
"message": message,
"encoded_img": convertToBase64(image: image1.image!)
]
let session = URLSession.shared
let url = URL(string: "http://xxxxxx/msg.php")!
var request = URLRequest(url: url, timeoutInterval: 20.0)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // not necessary, but best practice
request.setValue("application/json", forHTTPHeaderField: "Accept") // again, not necessary, but best practice; set this to whatever format you're expecting the response to be
request.httpBody = parameters.map { key, value in
let keyString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
let valueString = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
return keyString + "=" + valueString
}.joined(separator: "&").data(using: .utf8)
let dataTask = session.dataTask(with:request) { data, response, error in
guard error == nil,
let data = data,
let httpResponse = response as? HTTPURLResponse,
(200 ..< 300) ~= httpResponse.statusCode else {
print(error ?? "Unknown error", response ?? "Unknown response")
return
}
// process `data` here
}
dataTask.resume()
where
func convertToBase64(image: UIImage) -> String {
return UIImagePNGRepresentation(image)!
.base64EncodedString()
}
and
extension CharacterSet {
/// Character set containing characters allowed in query value as outlined in RFC 3986.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
static var urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
return allowed
}()
}
Alternatively, you could consider using Alamofire which gets you out of the weeds of creating well-formed x-www-form-urlencoded
requests.
Converting Image to BASE64 String in swift
Actually it will not take time to convert but for printing, it will take more time so don't print it...
Unable to decode base64string to uiimage in iOS swift but working fine in android
You do:
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
and
let imageData = Data(base64Encoded: base64, options: .init(rawValue: 0))
So you added an option for the encoding, but not for the decoding? Is the default" decoding working then? No need to specify that there was a perticular option set?
Let's see the doc of lineLength64Characters
:
Set the maximum line length to 64 characters, after which a line ending is inserted.
Let's the the doc of available Data.Base64DecodingOptions
, especially .ignoreUnknownCharacters
:
Modify the decoding algorithm so that it ignores unknown non-Base-64 bytes, including line ending characters.
See?
Use .ignoreUnknownCharacters
while decoding instead of .init(rawValue:0)
(which by the way could be simplified with []
, or simply not putting the parameter since []
is its default value).
Convert UIImage to base64 string in swift
Do it something like this:
For Encoding:
data.base64EncodedStringWithOptions([])
For decoding:
let url = URL(string: String(format:"data:application/octet-stream;base64,%@",base64String))
do {
let data = try Data(contentsOf: url!)
}catch {
}
How to convert the image to base64 after take a photo from camera or library
you could use something like this approach, using the .onDismiss()
to then convert your imageSelected
to base64 string using your ImageConverter
.
In ProfileView
,
.sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
}
func didDismiss() {
let b64Str = imageManager.imageToBase64(imageSelected)
print("\n---> b64Str: \(b64Str?.count) \n")
}
Also remove the ZStack
, or replace it by a VStack
EDIT-1: here some example code that works for me:
struct ProfileView: View {
let imageManager = ImageConverter()
@State var changeProfileImage = false
@State var openCameraRoll = false
@State var imageSelected = UIImage()
var body: some View {
VStack {
Button(action: {
openCameraRoll = true
}, label: {
Image(systemName: "plus")
// .profileImageMod()
})
if changeProfileImage {
Image(uiImage: imageSelected)
.resizable() // <-- here
.frame(width: 222, height: 222)
.foregroundColor(.white)
.background(Color.gray)
.clipShape(Circle())
} else {
Image(systemName: "questionmark")
.frame(width: 222, height: 222)
.foregroundColor(.white)
.background(Color.gray)
.clipShape(Circle())
}
}
.sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
}
}
func didDismiss() {
changeProfileImage = true
let b64Str = imageManager.imageToBase64(imageSelected)
print("\n---> b64Str: \(b64Str?.count) \n")
}
}
Related Topics
Pdf417 Decode and Generate The Same Barcode Using Swift
Add Assets to an Icloud Shared Photo Album Programmatically
How to Post Parameter with (+ Plus Sign) in Alamofire
Playing Multiple Wav Out Multiple Channels Avaudioengine
How to Use Enumerated in a List of Structs in Foreach Swiftui
How to Get Window Reference (Cgwindow, Nswindow or Windowref) from Cgwindowid in Swift
How to Remove The Fading Animation on .Ondelete Swiftui
Swift: How to Continuously Send an Action from a Nstextfield
Filter by Day from Nsdate in Realm, Swift
Didbegincontact Not Being Called Swift
Tapping Is Required Twice to Uncheck Table Cell
Cannot Use Mutating Member on Immutable Value of Type 'string'
Swift Coredata: Unable to Section Tableview Using Sectionnamekeypath with Custom Function
Swift Generics and Protocol Extensions
Get Children of Children in Firebase Using Swift
Firebase Remove Snapshot Children Swift
How to Get and Save The Mixed of Multiple Audios in to Single Audio in Swift