UIImagePickerControllerOriginalImage from camera is not calling in ios swift - ios

I am able select image from gallery and save to UIImageView but when trying of camera i can not able save the image in UIImageView. it calls didFinishPickingMediaWithInfo method but its going inside UIImagePickerControllerOriginalImage if case.
here is the code i used for camera and gallery picker:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerImageURL] as? URL {
if let data : Data = try? Data(contentsOf: pickedImage as URL)
{
print(data.format)
if data.format == "gif" {
let data = try? Data(contentsOf: pickedImage) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
let imageView = UIImage(data: data!)
let width = imageView?.size.width
let height = imageView?.size.height
let url = SaveItemFilemanager.sharedinstance.saveGifimage(data: data!)
addGifImage(url: url!, width: width!, height: height!)
} else {
if let photo = info[UIImagePickerControllerLivePhoto] as? PHLivePhoto {
let assetResources = PHAssetResource.assetResources(for: photo)
let asset = assetResources[1]
let url = SaveItemFilemanager.sharedinstance.saveLiveimage(data: asset)
print(url!)
let frameCount = 16
let delayTime = Float(0.2)
let loopCount = 0
let width = photo.size.width
let height = photo.size.height
let regift : Regift = Regift(sourceFileURL: url!, frameCount: frameCount, delayTime: delayTime, loopCount: loopCount)
addGifImage(url: regift.createGif()!, width: width, height: height)
} else if let normalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let width = normalImage.size.width
let height = normalImage.size.height
let url = SaveItemFilemanager.sharedinstance.saveimage(image: normalImage)
addImage(url: url!, width: width, height: height)
} else {
let normalImage = info[UIImagePickerControllerOriginalImage] as? UIImage
let width = normalImage?.size.width
let height = normalImage?.size.height
let url = SaveItemFilemanager.sharedinstance.saveimage(image: normalImage!)
addImage(url: url!, width: width!, height: height!)
}
}
}
}
dismiss(animated: true, completion: nil)
}
func showCamera() {
let imagePicker = UIImagePickerController()
if(UIImagePickerController .isSourceTypeAvailable(.camera))
{
imagePicker.delegate = self
imagePicker.sourceType = .camera
}
present(imagePicker, animated: true, completion: nil)
}
I checked even by keeping break point in didfinishpicking media it calls and dismissed immediately.

Related

How to make a function like a memo that can add a video from my library (I want it to be displayed in the text view)

I have tried the following ways(These) but none of them have been successful
How to make a function like a memo that can add a video from my library (I want it to be displayed in the text view)
(Below is my code)
extension DetailViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
videoURL = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerReferenceURL") ] as? NSURL
print(videoURL!)
do {
let asset = AVURLAsset(url: videoURL! as URL , options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
selectedImage = thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
}
if var selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
let attachment = NSTextAttachment()
if selectedImage.imageOrientation == .up || selectedImage.imageOrientation == .down {
let img = selectedImage.resizeImage(image: selectedImage, targetSize: CGSize(width: self.view.frame.width - 50, height: self.view.frame.height))
attachment.image = img.imageWithSpacing(insets: UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0))
} else {
let img = selectedImage.resizeImage(image: selectedImage, targetSize: CGSize(width: self.view.frame.width - 50, height: self.view.frame.height))
attachment.image = img.imageWithSpacing(insets: UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0))
}
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insert(attString, at: textView.selectedRange.location)
picker.dismiss(animated: true, completion: nil)
}
let player = AVPlayer(url: videoURL! as URL)
let playerController = AVPlayerViewController()
playerController.player = player
self.present(playerController, animated: true) {
player.play()
}
let newPosition = textView.endOfDocument
textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
dismiss(animated: true, completion: nil)
}
}
I want to know, how to put the selected video in the text view, and the position is correct, I am thinking, should I convert the videoURL into another format and put it in the NSTextAttachment, or is it really impossible to do so?

Apply filter to the specific Image Segmentation Matte

I need to get Teeth SegmentationMatte from the image, add some filter to it and save it to the new or to the original image.
Here is my current code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
pictureImageView.image = pickedImage
picture = pickedImage
if #available(iOS 13.0, *) {
let base = CIImage(cgImage: picture.cgImage!)
let maxcomp = CIFilter.maximumComponent()
maxcomp.inputImage = base
let makeup = maxcomp.outputImage
guard let pictureCgImage = picture.cgImage else { return }
let matte = CIImage(cgImage: pictureCgImage, options: [.auxiliarySemanticSegmentationTeethMatte : true,
.auxiliarySemanticSegmentationSkinMatte : false,
.auxiliarySemanticSegmentationHairMatte : false])
let blend = CIFilter.blendWithMask()
blend.backgroundImage = base
blend.inputImage = makeup
blend.maskImage = matte
let result = blend.outputImage
let context = CIContext()
guard let filteredImage = result,
let perceptualColorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let imageData = context.heifRepresentation(of: filteredImage, format: .RGBA8, colorSpace: perceptualColorSpace, options: [.semanticSegmentationTeethMatteImage: filteredImage]) else { return }
let neededImage = CIImage(data: imageData) // our image with filtered teeth
}
}
dismiss(animated: true, completion: nil)
}
As a result, I am expecting to have the original image with filtered teeth. But I'm getting the image with a filter added to the whole picture, not only the teeth matte.

Generating thumbnail from Video ends up always rotated in an UIImageView

I'm using UIImagePickerController to select a video or an image from the user's gallery. With the photos, there's no problem, everything is displayed the way it should be. The problem comes when I'm trying to generate a thumbnail for a video.
Basically, the thumbnail image could end up being displayed upside down or 90 degrees to the left or right. I'm not sure why it happens. Am I missing something or doing something wrong?
extension PostVC : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let videoUrl = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
if let thumbnail = self.generateThumbnailForImage(videoUrl) {
self.videoUrl = videoUrl
self.photoImageView.image = thumbnail
self.selectedImage = thumbnail
}
}
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
selectedImage = image
photoImageView.image = image
shareButton.isEnabled = true
}
dismiss(animated: true, completion: nil)
}
func generateThumbnailForImage(_ fileUrl: URL) -> UIImage? {
let asset = AVAsset(url: fileUrl)
let imageGenerator = AVAssetImageGenerator(asset: asset)
do {
let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1, timescale: 10), actualTime: nil) // 1 sec
return UIImage(cgImage: thumbnailCGImage)
} catch let err {
SVProgressHUD.showError(withStatus: err.localizedDescription)
}
return nil
}
}
It seems like setting the imageGenerator.appliesPreferredTrackTransform = true solves this issue.

Issue with getting url of image in Gallery

I'm converting the image I'm picking from the gallery into its URL like so...
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
let imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL
let imageName = imageURL?.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
self.localPath = photoURL.appendingPathComponent(imageName!)
do {
try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
print("File Saved")
imageArray.append(image)
} catch { //Error }
self.collectionView.reloadData()
} else { //Error here }
self.dismiss(animated: true, completion: nil)
}
Now if I have 2 images, I want to pass them one by one to my API call as a parameter. This I'm doing like so...
for imgURL in imageArray {
let url = "http://myapp.com/vw/images_upload"
let headers = [ "Content-Type":"application/x-www-form-urlencoded"]
let Parameters =
[
"image": imgURL,
"seller_id": id
] as [String : Any]
Alamofire.request(url, method: .post, parameters: Parameters, encoding: URLEncoding.httpBody, headers: headers)
.responseJSON { (response) in
if let httpResponse = response.response {
print("error \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 {
if let result = response.result.value as? [String:Any] {
if result["success"] as! Int == 0 {
print("Something went wrong!")
} else if result["success"] as! Int == 1 {
print("UPLOADED IMAGE SUCCESSFULLY!!")
}}}}}}
But in the parameter, in imgURL, I'm not getting the url of the image. Above I had got the url in the localPath. But I cannot loop through localPath as it gives an error. Also, in the imageArray, I'm passing the image which is not in the url format...it is in this format: <UIImage: 0x60800009f9f0> size {4288, 2848} orientation 0 scale 1.000000...How the url format can be passed into the imageArray, that I'm not able to understand.Could this be the issue..?
Also how can I get the url of the image so that I can pass it into the API call...? Please help...
hi what i understand here from your question is that you are setting an image to an imageview and you want to pass that image's path to an api.
so i have written a function to do the same with a resizing ability which you can avoid or modify according to your needs.
So pass your image picked by the image picker and a default name string (eg:"image1") and you will get the image path/url in return
func storeImage(image:UIImage, fileName:String) -> String {
var resizedImage = image
func storeImage(image:UIImage, fileName:String) -> String {
var resizedImage = image
if (image.size.width > 200) {
let width = 200.0 as CGFloat
let height = image.size.height * width / image.size.width
resizedImage = image.scaleImage(toSize: CGSize(width: width, height: height))!
}
else if (image.size.height > 200) {
let height = 200.0 as CGFloat
let width = image.size.width * height / image.size.height
resizedImage = image.scaleImage(toSize: CGSize(width: width, height: height))!
}
let imageData = NSData(data:UIImagePNGRepresentation(resizedImage)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs: String = paths[0]
let fullPath = docs.stringByAppendingPathComponent(path: fileName)
_ = imageData.write(toFile: fullPath, atomically: true)
return fullPath
}

Swift 3 load image from local directory

I'm new to iOS dev and cannot figure out how to load an image in an imageView from a local directory.
I use imagePickerController to pick an image, get its info, then use this information to display the image in the imageView.
Here is the code to pick the image and its info dictionary:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)!
imagesList.append(localPath)
picker.dismiss(animated: true, completion: nil)
}
Then, and here is where I'm looking for some help, I want to use either localPath or imageUrl to load the image in another imageView but cannot figure out how.
I tried
func changeImage(_ sender: Any) {
if imagesList.count > 0 {
let imageUrlPath = imagesList[indexList]
let urlString: String = imageUrlPath.absoluteString
imageView.image = UIImage(contentsOfFile: urlString)
indexList = (indexList + 1) % imagesList.count
}
}
But I cannot have something working.
Any idea how I can achieve that?
Thank you for your help.
You'll want to save a reference to PHAsset objects, not URL strings.
Start with defining your Array as:
var imagesList = [PHAsset]()
Then, in didFinishPickingMediaWithInfo:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true)
// get the selected image as a UIImage object
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
// save a PHAsset reference in imagesList array for later use
if let imageUrl = info[UIImagePickerControllerReferenceURL] as? URL{
let assets = PHAsset.fetchAssets(withALAssetURLs: [imageUrl], options: nil)
if let p = assets.firstObject {
imagesList.append(p)
}
}
}
Next, add a couple "convenience" functions:
func getAssetFullsize(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var img = UIImage()
option.isSynchronous = true
let w = asset.pixelWidth
let h = asset.pixelHeight
manager.requestImage(for: asset, targetSize: CGSize(width: w, height: h), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
img = result!
})
return img
}
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
let w = 100
let h = 100
manager.requestImage(for: asset, targetSize: CGSize(width: w, height: h), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
and finally, when you want to get the actual image:
func changeImage(_ sender: Any) {
if imagesList.count > 0 {
// get the full-size image from PHAsset
imageView.image = getAssetFullsize(asset: imagesList[indexList])
// or, just get a thumbnail-sized image
//imageView.image = getAssetThumbnail(asset: imagesList[indexList])
indexList = (indexList + 1) % imagesList.count
}
}
Naturally, you'll want to add appropriate error-checking, your own sizing, naming, tracking, etc... but I think this is the direction you want to head.

Resources