Where is the image captured from iOS? - swift

When using the default camera in swift, I use this to take the picture and then show it in an imageView:
#IBAction func takePhoto() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
dismissViewControllerAnimated(true, completion: nil)
}
But I want to take the image that I just took and store that image in a constant, but I don't know what is the image I took. I have tried using this as the image
UIImage(named: UIImagePickerControllerOriginalImage)
UIImage(named: "spect a string here") and UIImagePickerControllerOriginalImage returns me a string so that is why I thought that could be the image, but it seems that it won't work.

You can say something like:
var photo = UIImage() // Accessible from anywhere in the class
#IBAction func takePhoto() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
photo = info[UIImagePickerControllerOriginalImage] as? UIImage // Assign `photo` to the image
}
In the above code, photo is a variable accessible from anywhere in the class. Therefore, it is accessible from all of your functions and handlers. info[UIImagePickerControllerOriginalImage] as? UIImage is the image from the camera, and in the code, you're changing the variable photo to the image from the camera. Now, the image from the camera is available later from anywhere in that class.

Related

Swift UIImagePickerController problem with photo in iCloud and allowsEditing

I need help.
I use UIImagePickerController to load the avatar. I can take a picture from camera and you can choose a photo.
I have photos stored partly in iCloud, and only previews on the device, partly locally.
When choosing a local photo or from camera, we get to the area selection screen, image cropping.
So if the photo is stored in iCloud, then the following happens:
I select a photo, click done - the window closes, but there is no photo.
My code:
Code for choose photo from library
func openMediaDialog() {
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
DispatchQueue.main.async {
self.imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
//self.imagePicker.navigationItem.setHidesBackButton(false, animated: false)
//If you dont want to edit the photo then you can set allowsEditing to false
self.imagePicker.allowsEditing = true
self.imagePicker.delegate = self
self.present(self.imagePicker, animated: true, completion: nil)
}
} else if status == .denied {
self.alertCameraAccessNeeded(title: "Необходим доступ к фото!", message: "Для загрузки аватара необходим доступ к фото. Разрешить?")
}
})
}
DELEGATE:
override func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
/*
Get the image from the info dictionary.
If no need to edit the photo, use `UIImagePickerControllerOriginalImage`
instead of `UIImagePickerControllerEditedImage`
*/
guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
self.view.makeToast("Проблема с выбором изображения")
}
print(selectedImage)
....
NEXT STEP - UPLOAD IMAGE
I ask you to tell me how to make sure that the photos are downloaded from icloud, cropped as needed and loaded further according to the usual scenario to the server.
You will get PHAsset if your photos on iCloud.. use this function to get photos
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// it will be loaded asynchronously
loadImageFromPicker(info: info)
picker.dismiss(animated: true, completion: nil)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
guard let phAsset = info[.phAsset] as? PHAsset else {
return
}
// size doesn't matter, because resizeMode = .none
let size = CGSize(width: 32, height: 32)
let options = PHImageRequestOptions()
options.version = .original
options.deliveryMode = .highQualityFormat
options.resizeMode = .none
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: phAsset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
if let s = self, let image = image {
// use this image
}
}
}

How can I make this imagePickerController able to accept edited images?

How can I make this imagePickerController able to accept edited images?
When selecting an image and adjusting it (zoom in and out) and selecting done, the image reverts back to its original state. What can I add to to my code to have the zoomed image save and show up in my image view?
The following is my code so far:
let cameraRollAction = UIAlertAction(title: "Camera Roll", style: .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.mediaTypes = [kUTTypeImage as String]
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(picker, animated: true, completion: nil)
self.newPic = false
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profileImageView.image = selectedImage
if newPic == true {
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(imageError), nil)
}
}
self.dismiss(animated: true, completion: nil)
}
Instead of
UIImagePickerControllerOriginalImage
use
UIImagePickerControllerEditedImage
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage ?? info[UIImagePickerControllerOriginalImage] as! UIImage // will return original image if edited image is not available
profileImageView.image = selectedImage
if newPic == true {
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(imageError), nil)
}
}
self.dismiss(animated: true, completion: nil)
}

didFinishPickingMediaWithInfo function goes on infinite loop

It looks like the didFinishPickingMediaWithInfo function is going on an infinite loop and it eventually crashes with an error that says in the console:
warning: could not execute support code to read Objective-C class data in >the process. This may reduce the quality of type information available.
Right when I record a video and press the choose button, it crashes because it calls the didFinishPickingMediaWithInfo. Here is the relevant code:
let imagePicker: UIImagePickerController! = UIImagePickerController()
let saveFileName = "/test.mp4"
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
//if the camera is available, and if the rear camera is available, the let the image picker do this
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.allowsEditing = false
imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
imagePicker.videoMaximumDuration = 60
imagePicker.videoQuality = .typeIFrame1280x720
present(imagePicker, animated: true, completion: nil)
} else {
postAlert("Rear camera doesn't exist", message: "Application cannot access the camera.")
}
} else {
postAlert("Camera inaccessable", message: "Application cannot access the camera.")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(123)
imagePickerController(imagePicker, didFinishPickingMediaWithInfo: [saveFileName : kUTTypeMovie])
let videoURL = info[UIImagePickerControllerReferenceURL] as? NSURL
print("\(String(describing: videoURL))" )
guard let path = videoURL?.path else { return }
let videoName = path.lastPathComponent
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths.first as String!
let localPath = documentDirectory! + "/" + videoName
guard let imageData = NSData(contentsOfFile: localPath) else { return }
let image = UIImage(data: imageData as Data)
picker.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.imagePicker.delegate = self
}
Thank you in advance!
You are calling the function from inside of itself, here:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(123)
imagePickerController(imagePicker, didFinishPickingMediaWithInfo: [saveFileName : kUTTypeMovie])
That is causing your infinite loop.

xcode 8.1 & iOS 10.1.1 "[Generic] Creating an image format with an unknown type is an error" for UIImagePickerController

Trying to allow a user to select a photo from their photo library and then display that image in a UIImageView. Photo library is showing up just fine, but when I select a photo from my library, I get this error "[Generic] Creating an image format with an unknown type is an error".
Stepped through my code below but the error comes up only when selecting an image which does not occur inside either of these 2 functions.
#IBAction func openPhotoLibraryButton(sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage!
let imageData = UIImageJPEGRepresentation(image!, 0.6)
let compressedJPGImage = UIImage(data: imageData!)
imagePicked.image = compressedJPGImage
}
Tried the solutions suggested here: xCode 8 - Creating an image format with an unknown type is an error but none of them worked, and it sounds like several folks did not get this issue resolved. Any ideas?
did you try adding _ before picker? I believe the method was changed and the one you are using is deprecated, you should be able to let it autocomplete.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
if let imageData = UIImageJPEGRepresentation(image, 0.6) {
let compressedJPGImage = UIImage(data: imageData)
imagePicked.image = compressedJPGImage
}
} else {
print("Image Picker Failure")
//handle any possible image picker issues/failures so that app doesn't crash in the future
//troubleshoot further if it always hits this
}
dismissViewControllerAnimated(true, completion: nil)
}

How to convert image to binary in Swift

I created an app to take an image and convert this image to binary and send to server. I take the image but I can't convert it.
I use this code :
func cameraa(){
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
ImageDisplay.image = info[UIImagePickerControllerOriginalImage] as? UIImage;dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func Encode(sender: UIButton) {
var imageEncode = ImageDisplay.image
let image : UIImage = UIImage(imageEncode)
let imageData = UIImagePNGRepresentation(image)
print(imageData)
My error in parse image(imageEncode) to (let image : UIImage = UIImage(imageEncode))
The ImageDisplay.image is already a UIImage. So you needn't to convert it to UIImage again. Just do that:
let imageData = UIImagePNGRepresentation(ImageDisplay.image)
print(imageData)