So I've got an imagePickerController didFinishPickingMediaWithInfo implementation where I'm taking an image from the Camera and storing it as a local file:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print(info)
if let image = info["UIImagePickerControllerOriginalImage"] {
if let data = UIImagePNGRepresentation(image as! UIImage) {
let filename = getDocumentsDirectory().stringByAppendingPathComponent("CurrentProfilePicture.png")
data.writeToFile(filename, atomically: true)
}
}
self.imageController.dismissViewControllerAnimated(true, completion: nil)
}
I'm then displaying the image to the user with the following code in ViewDidAppear:
override func viewDidAppear(animated: Bool) {
let filename = getDocumentsDirectory().stringByAppendingPathComponent("CurrentProfilePicture.png")
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filename) {
let Profileimage1 = UIImage(contentsOfFile: filename)
let ciImage = CIImage(image: Profileimage1!)
let orientation1: UIImageOrientation = (Profileimage1?.imageOrientation)!
profileImage.image = UIImage(CIImage: ciImage!, scale: 1.0, orientation:orientation1)
}
}
If I just load the UIImage straight into the UIImageView I get the incorrect orientation. I tried the above and I still get the incorrect orientation. The Photo was taken with the camera in portrait with the phone the correct way up and it comes out rotated 90 degrees counter clockwise. If I check the data returned from the info dictionary in the didFinishPickingMediaWithInfo method it states orientation 3 although I'm not sure what this relates to. When the image is loaded in ViewDidAppear the orientation that is returned is "Up" but this is obviously incorrect. If I turn the phone landscape the orientation is again wrong.
What am I doing wrong? Thanks!
Related
In iOS Swift I'm having difficulty loading an animated GIF from the device photo library to a UIImageView or creating a .gif file from it. I have no problem displaying the animated GIF if it's a file on a server or if it's right in the app. However, when I load it from the photo library, I lose the animation. I found some Objective-C solutions and tried to convert them over to Swift, but haven't had any luck.
Here is what I have so far:
#IBAction func buttonTapped(sender: UIButton) {
selectPhoto()
}
func selectPhoto() {
let photoLibraryController = UIImagePickerController()
photoLibraryController.delegate = self
photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
let mediaTypes:[String] = [kUTTypeImage as String]
photoLibraryController.mediaTypes = mediaTypes
photoLibraryController.allowsEditing = false
self.presentViewController(photoLibraryController, animated: true, completion: nil)
}
// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let origImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.image = origImage
picker.dismissViewControllerAnimated(true, completion: nil)
}
Optimally, I would like to save the photo library image to a gif file on the server. From there I have no trouble displaying it. However, I need some help getting the data from the photo library into some type of property, without losing the animation. Do I need to use something like ALAssetsLibrary for this?
Thanks.
Yes, Use ALAssetsLibrary → now called PHAsset.
You should get the NSData of the gif, not UIImage( because UIImage will only get the first frame.)
So basically you would do something like this:
One you get the asset
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // adjust the parameters as you wish
PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, UTI, _, _) in
if let uti = UTI,let data = imageData ,
// you can also use UTI to make sure it's a gif
UTTypeConformsTo(uti as CFString, kUTTypeGIF) {
// save data here
}
})
Resource: PHAsset
You can get an access to the location of the image file using InfoKey .imageURL and retrieve Data from this URL
// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let path = info[.imageURL] as? URL {
if let data = try? Data(contentsOf: path) {
self.imageView.image = UIImage(data: data)
//Now you have Data of a file: so you can convert it to image or gif or send to server or start animation (e.g. Framework JellyGIF)
self.imageView.startGif(with: .data(data))
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
This question already has an answer here:
PDFKit is vertically flipping PDFPage initialised with image
(1 answer)
Closed 5 years ago.
When I use the camera to take a picture in my app the images are then displayed upside down.
I use a UIImagePickerController to take a photo and just select the one i am happy with. Upon selection, the following function is execute:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("image selected ...")
// Get picked image info dictionary
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Image is upside down. Need to re-orient
// Add captured and selected image to your Photo Library
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
// Create PDFDocument object and display in PDFView
let document = createPDFDataFromImage(image: image)
myPDFView.document = document
// Dimiss imagePicker
dismiss(animated: true, completion: nil)
}
func createPDFDataFromImage(image: UIImage) -> PDFDocument{
let document = PDFDocument.init()
let imagePDF = PDFPage.init(image: image)
document.insert(imagePDF!, at: 0)
return document
}
How can I stop the pictures from being upside down?
Here is one way to do it:
var flippedImage: UIImage?
if let origImage = UIImage(named: "s1") {
if let cg = origImage.cgImage {
flippedImage = UIImage(cgImage: cg, scale: 1.0, orientation: UIImageOrientation.downMirrored)
}
}
theImageView.image = flippedImage
Hi I am new to pdfkit and iOS applications, I want to take a picture with device and then convert the image to pdf. taking pictures with camera and saving it on Camera Roll works completely fine, the problem is when I want to create pdf from that image it needs the name of the image, how I can find it?
and another question is it possible to implement any pdf editor with pdfkit to edit image?
Appreciate any help. below is my imagePickerController codes.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
if (Mylibrary)
{
}
else
{
UIImageWriteToSavedPhotosAlbum(pickedImage!, nil, nil, nil);
let image = UIImage(named: "????") //the problem is here
let newPage = PDFPage(image: image!)
}
picker.dismiss(animated: true, completion: nil)
}
There's no need to instantiate a new image since the image is already stored in the pickedImage variable. You just need to initialize the new PDFPage object with pickedImage. Use ImageKit to edit the image before using it to initialize a new PDFPage object.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
// Adds pickedImage to the user’s Camera Roll album.
UIImageWriteToSavedPhotosAlbum(pickedImage, nil, nil, nil)
// Creates a new PDFPage object and initializes it with pickedImage.
let newPage = PDFPage(image: pickedImage)
dismiss(animated: true, completion: nil)
}
In iOS Swift I'm having difficulty loading an animated GIF from the device photo library to a UIImageView or creating a .gif file from it. I have no problem displaying the animated GIF if it's a file on a server or if it's right in the app. However, when I load it from the photo library, I lose the animation. I found some Objective-C solutions and tried to convert them over to Swift, but haven't had any luck.
Here is what I have so far:
#IBAction func buttonTapped(sender: UIButton) {
selectPhoto()
}
func selectPhoto() {
let photoLibraryController = UIImagePickerController()
photoLibraryController.delegate = self
photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
let mediaTypes:[String] = [kUTTypeImage as String]
photoLibraryController.mediaTypes = mediaTypes
photoLibraryController.allowsEditing = false
self.presentViewController(photoLibraryController, animated: true, completion: nil)
}
// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let origImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.image = origImage
picker.dismissViewControllerAnimated(true, completion: nil)
}
Optimally, I would like to save the photo library image to a gif file on the server. From there I have no trouble displaying it. However, I need some help getting the data from the photo library into some type of property, without losing the animation. Do I need to use something like ALAssetsLibrary for this?
Thanks.
Yes, Use ALAssetsLibrary → now called PHAsset.
You should get the NSData of the gif, not UIImage( because UIImage will only get the first frame.)
So basically you would do something like this:
One you get the asset
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // adjust the parameters as you wish
PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, UTI, _, _) in
if let uti = UTI,let data = imageData ,
// you can also use UTI to make sure it's a gif
UTTypeConformsTo(uti as CFString, kUTTypeGIF) {
// save data here
}
})
Resource: PHAsset
You can get an access to the location of the image file using InfoKey .imageURL and retrieve Data from this URL
// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let path = info[.imageURL] as? URL {
if let data = try? Data(contentsOf: path) {
self.imageView.image = UIImage(data: data)
//Now you have Data of a file: so you can convert it to image or gif or send to server or start animation (e.g. Framework JellyGIF)
self.imageView.startGif(with: .data(data))
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
Besides browsing the Photolibrary I've enabled the Camera to add a photo to my
#IBAction func startCameraButtonTapped(sender: AnyObject) {
let startCameraController = UIImagePickerController()
startCameraController.delegate = self
startCameraController.sourceType = UIImagePickerControllerSourceType.Camera
startCameraController.allowsEditing = true
self.presentViewController(startCameraController, animated: true, completion: nil)
//invoiceImageHolder.image!.scaleAndRotateImage2(280)
//self.invoiceImageHolder.transform = CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 180.0)
}
Every user input can be deleted, but now I'd like to know where the corresponding photo is. When I browse the photo library I can't see the photos taken with my app? Where are those photos stored?
[edit]
This is my saveImage process
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
saveImage(selectedImage, path: fileInDocumentsDirectory("\(uniqueImageName)"))
// set the unique image reference in textfield
// Set photoImageView to display the selected image
self.invoiceImageHolder.image = selectedImage
// Dismiss the picker
dismissViewControllerAnimated(true, completion: nil)
}
func saveImage(image: UIImage, path: String) -> Bool{
let pngImageData = UIImagePNGRepresentation(image)
// let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
let result = pngImageData?.writeToFile(path, atomically: true)
//print("Save result \(result)")
return result!
}
EDIT hmm I think I see where the photos are stored, but now how do I browse to them for deletions?
I think it's here:
/var/mobile/Containers/Data/Application/CBFE9E9D-A657-4011-8B9F-EF0C9BB2C603/Documents/
BUT everytime i restart the app the part between Application and /Documents is different??
Still not a working solution, but for those newbies as me this is a valuable readup: http://www.techotopia.com/index.php/Working_with_Directories_in_Swift_on_iOS_8
[EDIT 2]
with this code i am able to see all whiles stored with my app. I was a bit surprise to see all the files
// Files stored in my app filemanager
let filemgr = NSFileManager.defaultManager()
do {
print("Start filemanager")
let filelist = try filemgr.contentsOfDirectoryAtPath(documentsDirectory())
for filename in filelist {
print(filename)
}
} catch {
print("No directory path \(error)")
}
// end filemanager
UIImagePickerController() doesn't automatically save your photos into the library. See its UIImagePickerControllerDelegate protocol and you'll see that it has a method returning your UIImage after making a photo. Then you can save it:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
you save them - not in the photo library - but as 'simply' files inside your app's documents folder. There is no standard UI for deletion then.
You need to write your own ViewController to show & handle deletions then.