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.
Related
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.
Am creating an application for image share related things. Here my requirement is I have to store some custom information(Name, PhoneNumber, Price) into the Image Metadata and retrieve it back.
I use UIImagePickerController to capture the image and set my information into the image metadata in UIImagePickerControllerDelegate like below mentioned:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
let profileImage = info[UIImagePickerControllerOriginalImage] as? UIImage
let imageData: Data = UIImageJPEGRepresentation(profileImage!, 1)!
let cgImgSource: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil)!
let uti: CFString = CGImageSourceGetType(cgImgSource)!
let dataWithExif: NSMutableData = NSMutableData(data: imageData)
let destination: CGImageDestination = CGImageDestinationCreateWithData((dataWithExif as CFMutableData), uti, 1, nil)!
let imageProoperties = CGImageSourceCopyPropertiesAtIndex(cgImgSource, 0, nil)! as NSDictionary
let mutable: NSMutableDictionary = imageProoperties.mutableCopy() as! NSMutableDictionary
let EXIFDictionary: NSMutableDictionary = (mutable[kCGImagePropertyExifDictionary as String] as? NSMutableDictionary)!
print("Before Modification: \(EXIFDictionary)")
EXIFDictionary[kCGImagePropertyExifUserComment as String] = "\(self.m_NameTxtFd.text!):\(self.m_PhoneNumberTxtFd.text!):\(self.m_PriceTxtFd.text!)"
mutable[kCGImagePropertyExifDictionary as String] = EXIFDictionary
CGImageDestinationAddImageFromSource(destination, cgImgSource, 0, (mutable as CFDictionary))
CGImageDestinationFinalize(destination)
let testImage: CIImage = CIImage(data: dataWithExif as Data, options: nil)!
let newProperties: NSDictionary = testImage.properties as NSDictionary
print("After Modification : \(newProperties)") //Here I Got My Information is Stored Successfully
self.m_ImgView.image = self.convert(cmage: testImage)
self.saveImageDocumentDirectory()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
Now am going to save the image in NSDocumentDirectory like below mentioned:
func saveImageDocumentDirectory(){
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("apple.jpg")
let image = self.m_ImgView.image
print(paths)
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
}
Now am going to fetch the stored image in another view controller like below mentioned:
func getImage(){
let fileManager = FileManager.default
let imagePAth = (self.getDirectoryPath() as NSString).appendingPathComponent("apple.jpg")
print(imagePAth)
if fileManager.fileExists(atPath: imagePAth){
self.m_ImgView.image = UIImage(contentsOfFile: imagePAth)
self.fetchImageDetails()
}else{
print("No Image")
}
}
I successfully got the image and now I have to fetch the information from image metadata like below mentioned:
func fetchImageDetails() {
let profileImage = self.m_ImgView.image!
let ciImage: CIImage = CIImage(cgImage: profileImage.cgImage!)
let newProperties: NSDictionary = ciImage.properties as NSDictionary
}
But issue is the information is null in image property.
Please guide me to retrieve the custom information from stored Image.
First create NSMutableDictionary and set value to NSMutableDictionary when you set value to then you don't need to set again to metadata you directly assign to NSMutableDictionary to Metada.
let metadata = info[UIImagePickerControllerMediaMetadata] as? NSMutableDictionary
let exifData = NSMutableDictionary()
let metaStr = "\(self.m_NameTxtFd.text!),\(self.m_PhoneNumberTxtFd.text!),\(self.m_PriceTxtFd.text!)"
exifData.setValue(metaStr, forKey: kCGImagePropertyExifDictionary as String)
metadata = exifData
fileManager.requestImageData(for: fetchResult.object(at: i) as PHAsset, options: requestOptions, resultHandler: { (imagedata, dataUTI, orientation, info ) in
if let info = info {
if info.keys.contains(NSString(string: "PHImageFileURLKey")) {
path = info[NSString(string: "PHImageFileURLKey")] as? NSURL
size = (imagedata! as NSData).length
self.name = PHAssetResource.assetResources(for:fetchResult.object(at: i)).first?.originalFilename
self.imageData = imagedata
}
}
})
I want to get EXIF data from images in my PhotoLibrary but cannot find the correct method. I have used answers from this question, and this one. I'm getting the following console output:
imageSource: <UIImage: 0x6080000b8a20> size {3000, 2002} orientation 0 scale 1.000000
2017-09-18 11:24:28.513567+0300 PhotoTest[10581:6526935] CGImageSourceCopyPropertiesAtIndex:3517: *** ERROR: CGImageSourceCopyPropertiesAtIndex: source is not a CGImageSourceRef
2017-09-18 11:24:29.071412+0300 PhotoTest[10581:6527417] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
This is my current code attempt. I'd appreciate any solutions or ideas. I've been scratching my head trying to divine various methods, but I don't know enough about imageIO to solve the problem.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
let bigImage = info[UIImagePickerControllerOriginalImage] as? UIImage
photoImageView.image = bigImage
imageData = UIImagePNGRepresentation(bigImage!) as NSData?
if let imageSource = info[UIImagePickerControllerOriginalImage] {
print("imageSource: ", imageSource)
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource as! CGImageSource, 0, nil)
//print("imageProperties: ", imageProperties!)
if let dict = imageProperties as? [String: Any] {
print(dict)
}
}
dismiss(animated: true, completion: nil)
}
You're seeing the:
*** ERROR: CGImageSourceCopyPropertiesAtIndex: source is not a CGImageSourceRef
line because you need to create your imageSource via one of the CGImageSourceCreate... API's.
Try doing this:
if let bigImage = info[UIImagePickerControllerOriginalImage] as? UIImage
{
if let imageData = UIImagePNGRepresentation(bigImage)
{
if let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil)
{
print("imageSource: ", imageSource)
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
//print("imageProperties: ", imageProperties!)
if let dict = imageProperties as? [String: Any] {
print(dict)
}
}
}
}
I found a different solution, as follows:
import Photos
import PhotosUI
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let assetURL = info[UIImagePickerControllerReferenceURL] as! NSURL
let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL as URL], options: nil)
guard let result = asset.firstObject else {
return
}
let imageManager = PHImageManager.default()
imageManager.requestImageData(for: result , options: nil, resultHandler:{
(data, responseString, imageOriet, info) -> Void in
let imageData: NSData = data! as NSData
if let imageSource = CGImageSourceCreateWithData(imageData, nil) {
let imageProperties2 = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)! as NSDictionary
print("imageProperties2: ", imageProperties2)
}
})
dismiss(animated: true, completion: nil)
}
Hope this helps others.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let exifData = info[.mediaMetadata] as? [String: Any] {
//print(exifData)
}
}
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")
I would like to save the URL of the photos have been taken from the camera or exinting in the camera roll and have been selected.
Your question is extremely vague with nothing for us to work with. But in any case, I just created an app requiring that logic so I would just share with you
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// Clear data if picture is repicked
imageLocalURL = nil
imageData = nil
imageSelected = info[UIImagePickerControllerOriginalImage] as? UIImage
if info[UIImagePickerControllerReferenceURL] != nil {
// This would mean that image is chosen from photo library
referenceURL = info[UIImagePickerControllerReferenceURL] as? NSURL
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceURL! as NSURL], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (contentEditingInput, info) in
// This would be the URL of your image in photo library
self.imageLocalURL = contentEditingInput?.fullSizeImageURL
} else {
// This means that image is taken from camera
imageData = UIImageJPEGRepresentation(imageSelected!, 1.0)
}
dismissViewControllerAnimated(true, completion: nil)
}