Converting Image to BASE64 String in swift - ios

I am trying to convert the Image which is picked by user either from his Photos or Take New from Camera. I am able to convert the image into base64 string but the problem is that it takes too much time and prints a long infinite string
Here is the output of String which i am getting
here is my code:
// Image picker from Gallery
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
profileImage.image = image
}
// Image Picker from Camera
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
profileImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
addPicBtn.setImage(nil, forState: .Normal)
let imageData:NSData = UIImagePNGRepresentation(profileImage.image!)!
let imageStr = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(imageStr)
}

Actually it will not take time to convert but for printing, it will take more time so don't print it...

You can apply this code
let imageData: Data? = UIImageJPEGRepresentation(getImage(), 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(strBase64)

Swift 4 version. This simple func worked well for me. Confirmed decoded image back using this: https://codebeautify.org/base64-to-image-converter
Hope this helps someone.
public static func convertImageToBase64String(image : UIImage ) -> String
{
let strBase64 = image.pngData()?.base64EncodedString()
return strBase64!
}

Make sure your image extension first.
// .png
guard let imageData = UIImagePNGRepresentation(UIImage) else {
return ""
}
// .JPEG
guard let imageData = UIImageJPEGRepresentation(UIImage, 1) else {
return ""
}
// BASE 64
imageData.base64EncodedString()

let imageData: Data? = UIImageJPEGRepresentation(YourImage, 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(imageStr,"imageString")

Related

How to crop image in freestyle(as user wants) while selecting from image picker in ios

can any one help me in cropping image in freestyle as user wants.
I tried the below method, but its cropping image only in square shape.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage{
pickImage.image = image
let imageData:NSData = UIImageJPEGRepresentation(pickImage.image!, 0.5) as! NSData
if(imageData != nil){
// let imageStr1 = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let imageStr1 = imageData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
imageStr = "data:image/png;base64,\(imageStr1))"
}
}
dismiss(animated: true, completion: nil)
}
Please try to answer me with apple default methods, if available.
Thanks in advance.

Swift 4.2 Cannot convert value of type '(UIImagePickerController.InfoKey).Type' to expected argument type 'UIImagePickerController.InfoKey'

My below code was working just fine with swift 4 but after upgrading to swift 4.2 I am getting this error, I had wasted my 3 hours searching what's the issue but failed. Please if anyone can guide me how to fix this.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if postType == 2 {
let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey)] as! UIImage
mediaType.image = image
} else {
videoURL = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.mediaURL)] as? URL
do {
let asset = AVURLAsset(url: videoURL!, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTime.init(value: 0, timescale: 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
self.mediaType.image = thumbnail
} catch {
print("*** Error generating thumbnail: \(error)")
}
}
picker.dismiss(animated: true, completion: nil)
}
You can write like...
if let image = info[.originalImage] as? UIImage {
print("image found")
//do something with an image
} else {
print("Not able to get an image")
}
EDIT:
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//for original image
let originalImage = info[.originalImage]
//for edited image
let editedImage = info[.editedImage]
if #available(iOS 11.0, *) {
//gives URL of image picked by user
let imageURL = info[.imageURL]
}
//gives URL of media picked by user
let mediaURL = info[.mediaURL]
}
info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey)]
does not make any sense. You are specifying the whole enum type InfoKey instead of a specific value, e.g.:
info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)]
Which can be probably also written just as:
info[.originalImage] as! UIImage
You can access the properties as follows.
var editedImage = (info[UIImagePickerControllerEditedImage] as? UIImage)!
var originalImage = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
if picker.sourceType == .photoLibrary || picker.sourceType == .camera
{
let img: UIImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.editedImage)] as! UIImage
EditedImage=img
WAProfile_UserImageView.image=EditedImage
picker.dismiss(animated: true, completion: nil)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
yourImgView.image = image
}
Although an old thread, the migrator added this function which seemed to fix things nicely:
// Function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input:
[UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}

How to upload an image using Alamofire SwiftyJSON to a JSON swift 3

I'm trying to send an image to my API using alamofire and SwiftyJSON. I've been trying some different ways to do that, however no success so far. The last one I tried is the base64EncodedString and is not working. I have the variable styleStrength as a JSON.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.profileImage.image = image
self.profileImage.isHidden = false
self.profileImage.contentMode = UIViewContentMode.scaleAspectFill
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedString(options: [])
var styleStrengthData = JobSeekerBuildProfile.loadJobSeekerBuildProfile()
styleStrengthData["Personal_Style"]["profile_pic_file"].stringValue = base64String + ".jpg"
JobSeekerBuildProfile.storeJobSeekerBuildProfile(j: styleStrengthData)
}else{
//error message
}
self.dismiss(animated: true, completion: nil)
}
As return I have a really huge image name but the API doesn't update.
Try to use the UIImageJPEGRepresentation instead of UIImagePNGRepresentation.
Replace these lines in your code
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedString(options: [])
styleStrengthData["Personal_Style"]["profile_pic_file"].stringValue = base64String + ".jpg"
with the
let imageData = UIImageJPEGRepresentation(image,0.5)! as NSData
let strBase64ProfilePic = imageData.base64EncodedString()
styleStrengthData["Personal_Style"]["profile_pic_file"].stringValue = base64String

iOS Swift Cannot acces EXIF data on stored photo

I need to get location of the pics in the device photo gallery. To do so I am trying to load the Exif data of the image.
This is my code:
import ImageIO
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
let ciImage = CIImage(image: image!)
let imageProperties = CGImageSourceCopyPropertiesAtIndex(ciImage as! CGImageSource, 0, nil) as Dictionary?
if let dict = imageProperties as? [String: Any] {
print(dict)
}
}
When I try to run my code on the device, the App crash.
I think the problem is in the cast, I tried to do some manipulaiton, but I am not able to convert my UIImage in CFImageSource type.
You can't cast a CIImage (nor a UIImage) to a CGImageSource. To create a CGImageSource do:
guard let imageData = UIImageJPEGRepresentation(uiImage, 1)
else { fatalError("Error getting image data") }
guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil)
else { fatalError("Error creating image source") }
let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
UIImageJPEGRepresentation returns the image as a JPEG image so it doesn't matter what format uiImage originally is in.

why imageData Will return nil in swift 3?

hi I want to convert images into Data but the problem is that the Data will return nil
I want to upload images with Alamofire so I need to convert images before using Alamofire upload here is my codes
let imageData = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0)
Alamofire.upload(imageData! , to: "http://example.com/api/file?api_token=\(api_token)&id=\(postID)").responseJSON { response in
debugPrint(response)
}
Try below code to get imageData and make sure you are passing right image there not nil,
For PNG:-
let data = UIImagePNGRepresentation(ViewController.imageUpload[i]) as NSData?
For JPEG:-
let data = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0) as NSData?
And also check which image extension you are using while saving (PNG or JPEG)
To know the image extension, please have a look into below code,
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if (!(picker.sourceType == UIImagePickerControllerSourceType.Camera)) {
let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
if assetPath.absoluteString.hasSuffix("JPG") {
}
}
}

Resources