add/modify/edit the photo's exif in swift - exif

I am building an app which can add/modify/edit the exif after the photo filtered. The photo miss all the exif after adding filter. I have try added the new exif to the photo by attempting using the code below, which is not work. The exif still blank in the Mac App - Photos. How to fix it?
THX
//Code below
imageData = UIImageJPEGRepresentation(outp, 1.0)
let imageSource = CGImageSourceCreateWithData(imageData! as CFData, nil)
let filePath = NSTemporaryDirectory().appending("example.jpg")
let fileURL = URL.init(fileURLWithPath: filePath)
var imageInfo = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as! Dictionary<CFString, Any>
var exifDictionay = Dictionary<CFString, Any>()
exifDictionay = imageInfo[kCGImagePropertyExifDictionary] as! Dictionary<CFString, Any>
exifDictionay[kCGImagePropertyExifExposureTime] = "1/3"
exifDictionay[kCGImagePropertyExifISOSpeed] = "200"
exifDictionay[kCGImagePropertyExifFNumber] = "2.4"
exifDictionay[kCGImagePropertyExifApertureValue] = "3.5"
exifDictionay[kCGImagePropertyExifFlash] = "On"
imageInfo[kCGImagePropertyExifDictionary] = exifDictionay
let UTI = CGImageSourceGetType(imageSource!)
let newImageData = NSMutableData()
CGImageDestinationAddImageFromSource(destination!, imageSource!, 0, imageInfo as CFDictionary)
CGImageDestinationFinalize(destination!)
PHPhotoLibrary.shared().performChanges({
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: PHAssetResourceType.photo, data: newImageData as Data, options: nil)
}, completionHandler: nil)

Related

how to add AuiliaryData(kCGImageAuxiliaryDataTypeHDRGainMap) to a heic image?

I use the 'CGImageDestinationAddAuxiliaryDataInfo' try to add Auxiliary Data, this method can add a AVDepthData as AuxiliaryData to heic image.
But, this method can't help me.
my code is:
func combo(jpgfile:String, hdrGainMap: String, to heicfile:String){
let jpgImage = NSImage(contentsOfFile: jpgfile)
let url = URL(fileURLWithPath: jpgfile)
let cijpg = CIImage(contentsOf: url)
let outputURL: URL? = URL(fileURLWithPath: heicfile)
guard let cgImageDestination = CGImageDestinationCreateWithURL(outputURL! as CFURL, kUTTypeJPEG, 1, nil) else {
return
}
let context = CIContext(options: nil)
let dict: NSDictionary = [
kCGImageDestinationLossyCompressionQuality: 1.0,
kCGImagePropertyIsFloat: kCFBooleanTrue,
]
if let cgImage: CGImage = context.createCGImage(cijpg!, from: cijpg!.extent) {
CGImageDestinationAddImage(cgImageDestination, cgImage, nil)
}
var auxDataType: NSString?
var auxDic = {kCGImageAuxiliaryDataInfoData}
let gainurl = URL(fileURLWithPath: hdrGainMap)
let gainImage = CIImage(contentsOf: gainurl)
let cgGainImage = context.createCGImage(gainImage!, from: gainImage!.extent)
let bytesPerRow = cgGainImage!.bytesPerRow
let width = cgGainImage!.width
let height = cgGainImage!.height
let pixelFormat = cgGainImage?.pixelFormatInfo.rawValue
let gainData = cgGainImage?.dataProvider?.data
let auxDataDic = [kCGImageAuxiliaryDataInfoData:gainData,
kCGImageAuxiliaryDataInfoDataDescription:["BytesPerRow":bytesPerRow, "width":width, "height":height,"Orientation":1,"pixelFormat":pixelFormat]
] as [String : Any]
CGImageDestinationAddAuxiliaryDataInfo(cgImageDestination, kCGImageAuxiliaryDataTypeHDRGainMap, auxDataDic as CFDictionary)
CGImageDestinationFinalize(cgImageDestination)
}
But,the code above will cause a runtime error:
(Fig) signalled err=-17102

Xamarin.iOS add left image to UILable

Here is my case I have custom control that inherent from UILable
and I need to create method that take image (from code or storyboard)
to be added to my label
My tries to convert this code to Xamarin.iOS Source
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.appendAttributedString(attachmentString)
label.attributedText = myString
public void SetLeftDrawable(UIImage image){
var attachment = new NSTextAttachment();
attachment.Image = image;
var attachmentString = new
NSAttributedString(attachment,null); // this method take string not NSTextAttachment
}
any one could help me
Try this:
public void SetLeftDrawable (UIImage image)
{
var attachment = new NSTextAttachment ();
attachment.Image = image;
var attachmentString = NSAttributedString.FromAttachment (attachment);
//replace "price" with your string.
var myString = new NSMutableAttributedString ("price");
myString.Append (attachmentString);
AttributedText = myString;
}
Hope this helps.-

Base64 encode decode for image URL in Swift 3

This is how I encoded:
let url:NSURL = NSURL(string : pictURL)!
let imageData : NSData = NSData.init(contentsOf: url as URL)!
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// next line my code to save in core data just ignore it
The value for encoded data = 3286 bytes. I think it is wrong
let pictEncoded = person.value(forKeyPath: "pictureurl") as! String
if let imageData = Data(base64Encoded: pictEncoded, options: .ignoreUnknownCharacters),
let image = UIImage(data: imageData)
{
cell.imgView.image = image
}

Swift + ios 9, sending post data with base64 image data

I have looked at the different questions related to send a post request with NS on swift. I am having issues however with the following code where the responding server doesn't even see it as being a post request.
What am I missing:
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var imageData = UIImageJPEGRepresentation(img, 0.6)
var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
var err: NSError? = nil
var params = ["image":[ "content_type": "image/jpeg", "filename":"\(self.riderid).jpg", "file_data": base64String]]
println("Image params \(params)")
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(0), error: &err)!
var task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err: NSError?
println("Image Response \(err) \(data)")
// process the response
var hoge = JSON(data: data!)
println("Image Response \(hoge)")
})
You need task.resume() after task block.
I know it's late replay but maybe it's help someone
var base64String = Detail.image.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
print(base64String)
var base64String2 = base64String.replacingOccurrences(of: "+", with: "%2B", options: NSString.CompareOptions.literal, range: nil)
base64String2 = base64String.replacingOccurrences(of: "/", with: "%2F", options: NSString.CompareOptions.literal, range: nil)
print(base64String2)
Do something like this
func insertDoctor_Detailmaster(_ Detail:DoctorDetail, isInsertOrUpdate:String){
var request:NSMutableURLRequest!
var postString:String
var base64String = Detail.image.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
print(base64String)
var base64String2 = base64String.replacingOccurrences(of: "+", with: "%2B", options: NSString.CompareOptions.literal, range: nil)
base64String2 = base64String.replacingOccurrences(of: "/", with: "%2F", options: NSString.CompareOptions.literal, range: nil)
print(base64String2)
if(isInsertOrUpdate == "insert"){
request = NSMutableURLRequest(url: URL(string: link.commonlink + "insert_doctor_master.php")!)
param = "doctor_id=\(Detail.doctor_id)&first_name=\(Detail.first_name)&last_name=\(Detail.last_name)&mid_name=\(Detail.mid_name)&speciality=\(Detail.speciality)&dob=\(Detail.dob)&gender=\(Detail.gender)&address_id=\(Detail.address_id)&mobile_number=\(Detail.mobile_number)&user_image=\(base64String2)"
_ = SD.executeChange(sqlStr: "INSERT INTO doctor_master (doctor_id, first_name,last_name, mid_name, dob, gender,doctorImage,speciality, address_id, mobileNumber) VALUES ('\(Detail.doctor_id)','\(Detail.first_name)','\("")','\(Detail.mid_name)','\(Detail.dob)','\(Detail.gender)','\(base64String)','\(Detail.speciality)','\(Detail.mobile_number)','\(Detail.mobile_number)')")
}else{
request = NSMutableURLRequest(url: URL(string: link.commonlink + "update_doctor_master.php")!)
param = "doctor_id=\(Detail.doctor_id)&first_name=\(Detail.first_name)&last_name=\(Detail.last_name)&mid_name=\(Detail.mid_name)&speciality=\(Detail.speciality)&dob=\(Detail.dob)&gender=\(Detail.gender)&address_id=\(Detail.address_id)&mobile_number=\(Detail.mobile_number)&\(base64String2)"
_ = SD.executeChange(sqlStr: "UPDATE doctor_master SET doctor_id = \(Detail.doctor_id), firstName ='\(Detail.first_name)',last_name = '\("")', mid_name ='\(Detail.mid_name)', dob ='\(Detail.dob)',gender = '\(Detail.gender)',doctorImage='\(base64String)',speciality='\(Detail.speciality)', address_id ='\(Detail.mobile_number)',mobileNumber = '\(Detail.mobile_number)'")
}
print(param)
postString = "q=\(AGS().encrypt(PlainText: param!))"
request.httpMethod = "POST"
request.httpBody = postString.data(using: String.Encoding.utf8)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {data,response,error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(responseString!)
res.variable.dosage = responseString as! String
}
task.resume()
print(postString)
}
Make sure your Session object's configuration for your request and as JMStudios.jrichardson said , write task.resume() after task block.

Instagram sharing not working on iOS 9

This worked fine on iOS 8, but on iOS 9 the UIDocumentInteractionController does appear with the option Copy to Instagram. Pressing it just dismisses the controller.
Any feedback would be appreciated.
Thanks,
var docController = UIDocumentInteractionController()
let instagramURL = NSURL(string: "instagram://app")
if(UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
var imagePost = cropped
let fullPath = documentsDirectory().stringByAppendingString("insta.igo")
var imageData = UIImagePNGRepresentation(imagePost!)!.writeToFile(fullPath, atomically: true)
let rect = CGRectMake(0, 0, 0, 0)
self.docController.UTI = "com.instagram.exclusivegram"
let igImageHookFile = NSURL(string: "file://\(fullPath)")
self.docController = UIDocumentInteractionController(URL: igImageHookFile!)
self.docController.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
return documentsFolderPath
}
The way iOS9 reads it when declaring "insta.igo", now needs to have the "/"
let fullPath = documentsDirectory().stringByAppendingString("/insta.igo")
Complete code
var docController = UIDocumentInteractionController()
let instagramURL = NSURL(string: "instagram://app")
if(UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
var imagePost = cropped
let fullPath = documentsDirectory().stringByAppendingString("/insta.igo")
var imageData = UIImagePNGRepresentation(imagePost!)!.writeToFile(fullPath, atomically: true)
let rect = CGRectMake(0, 0, 0, 0)
self.docController.UTI = "com.instagram.exclusivegram"
let igImageHookFile = NSURL(string: "file://\(fullPath)")
self.docController = UIDocumentInteractionController(URL: igImageHookFile!)
self.docController.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
return documentsFolderPath
This solution provided by Andy Shephard worked for me:
https://stackoverflow.com/a/32616355/1500708

Resources