Xcode Swift How do i rotate a portrait image to landscape - xcode

Hope someone can help me.
I have a imagepicker where pictures are taken as a portrait . My image is then displayed in an UIImageView where the width is greater than the height which makes the image looks wrong . How can I show the picture in my uiimageview in the landscape ? Is it possible to rotate the image in the imageview ?
my code for imagepicker are:
func openCamera() {
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(imagePicker, animated: true, completion: nil)
} else {
openGallary()
}
}
func openGallary() {
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
self.presentViewController(imagePicker, animated: true, completion: nil)
} else {
popover=UIPopoverController(contentViewController: imagePicker)
}
}
internal func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
photoURL = saveImageToFile(image)
self.dismissViewControllerAnimated(true, completion: nil)
}

Related

open new view controller from UIViewCell

// In UITableViewCell
// when I tab on screen it says "open image
2017-11-22 13:15:31.023129+0530 chat[1376:265960] Warning: Attempt to present on whose view is not in the window hierarchy!"
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.window?.rootViewController?.present(vc, animated: true, completion: nil)
}
You need to get the top presented view controller and then present.
Try this.
func topViewController() -> UIViewController? {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.topViewController()?.present(vc, animated: true, completion: nil)
}
On a separate note, You shouldn't use class name starts with small letter. openimageinfullscreen class should be OpenImageInFullscreen

Saving UIImageView Locally

Right now I am able to have the user successfully take a picture using the camera and have their picture be uploaded into a imageview. However, if the user leaves that view controller when they eventually return the photo is no longer in that imageview. Is there anyway I am able to save the photo so that once a picture is taken and put into that imageview it is there until the user takes a different picture to replace it?
import UIKit
class ArsenalViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var ball1: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func addPhoto1(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
ball1.contentMode = .scaleToFill
ball1.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
First you need to save the image data somewhere (i.e. UserDefaults, Core Data, a database) and then retrieve it. UserDefaults is easy, try this:
//Encoding
let imageData:NSData = UIImageJPEGRepresentation(pickedImage!)! as NSData
//Saved image
UserDefaults.standard.set(imageData, forKey: "savedImage")
//Decode
if let data = UserDefaults.standard.object(forKey: "savedImage") as! NSData{
myImageView.image = UIImage(data: data as Data)
}
Encoding and saving image should happen right after updating your image and decoding should be done once the view has loaded all of its elements (viewDidAppear method).
After encoding and saving the image once, you can decode it anytime, even if the user left the VC and came back.

Swift 3 - Cannot override 'imagePickerController'

My code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.image = image
self.imageStatusLabel.text = "There is a picture"
self.imageStatusLabel.textColor = UIColor.blue()
picker.dismiss(animated: true, completion: nil)
}
And this is the error:
Cannot override 'imagePickerController' which has been marked unavailable: APIs deprecated as of iOS 7 and earlier are unavailable in Swift
Well, I've tried to use the newer function:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// But no image in the parameters
}
But then, there is no image in the parameters and I can get the image.
What should I do?
You have to use the info parameter and make a cast to UIImage. Don't forget that you have to put a "Privacy - Photo Library Usage Description" and a "Privacy - Camera Usage Description" in the info.plist file and fill the values with a string explaining the reason for request the access to photo library and camera.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
pictureImageView.contentMode = .scaleToFill
pictureImageView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
To use imagePickerController in Swift3 you need add a row with key: Privacy - Photo Library Usage Description and value is a string (e.g: "Access to your photos") to Info.plist file and let's try below:
class YourController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePickerButton: UIButton = {
let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
btn.setTitle("Choose a Photo", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.backgroundColor = .blue
btn.addTarget(self, action: #selector(handlePickerDidTap), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imagePickerButton)
}
func handlePickerDidTap() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("photo is selected")
// do some thing here
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
Hope it help!
You get the image from the passed info dictionary, see the keys in the documentation
You probably want either
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
or
let image = info[UIImagePickerControllerEditedImage] as? UIImage
import UIKit
import Photos
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBAction func selectPhotoLibrary(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = .camera
} else{
print("Kamera desteklenmiyor.")
}
present(picker, animated: true, completion:nil)
}
#IBAction func selectPhotoCamera(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
guard let imageData = UIImageJPEGRepresentation(image, 0.8) else { return }
self.imageView.image = image
print(imageData)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Read more for usage detail --> https://medium.com/#yakupad/swift-uiimagepickercontroller-kullanımı-91771ed4c1d6

Is here a simple way to pick image and upload it?

I am calling to all swift developers here. I am struggling last 3 days with this topic. Is there a way to pick an image from image picker (local photo library of iPhone) and upload it to server? I can't figure out how to do this....just tons of outdated code or nothin.
You should try to use a UIImagePickerController like this
#IBAction func takePhoto(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self;
picker.allowsEditing = true;
picker.sourceType = .PhotoLibrary;
self.presentViewController(picker animated:true completion:nil);
}
Then you can get the image in imagePickerController(_:didFinishPickingMediaWithInfo:) method from UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage
UploadImage(chosenImage)
picker.dismissViewControllerAnimated(true, completion: nil);
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil);
}
Finally you upload the image. Example using HTTP POST Check this answer
function UploadImage(image : UIImage) {
var imageData = UIImagePNGRepresentation(image)
if imageData == nil {
print("image not valid")
return
}
// Upload
....
}
Note This answer is directly written in the reply, please change any invalid code.

How do I add an image filter only in the touch radius in swift

I am new to swift and I have an app which allows the user to get a picture from their camera roll and display it in an imageview. I have found plenty of tutorials on how to add filters, but how do I isolate this to a touch radius, not the entire image?
import UIKit
import AVFoundation
import Social
import MobileCoreServices
import MessageUI
import iAd
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate, UITextFieldDelegate, UITextViewDelegate {
#IBOutlet var imageView: UIImageView!
let picker = UIImagePickerController()
var cameraUI: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func filter(sender: UIButton) {
let myPicture = imageView.image
let filter = CIFilter(name: "CIPhotoEffectMono")
filter.setValue(CIImage(image: myPicture), forKey: kCIInputImageKey)
let newImage = UIImage(CIImage: filter.outputImage)
imageView.image = newImage
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let myPicture = imageView.image
for obj in touches {
let touch = obj as! UITouch
let location = touch.locationInView(self.view)
}
}
#IBAction func getImageButton(sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
{
cameraUI = UIImagePickerController()
cameraUI.delegate = self
cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
cameraUI.mediaTypes = [kUTTypeImage]
cameraUI.allowsEditing = false
self.presentViewController(cameraUI, animated: true, completion: nil)
}
else
{
let alertVC = UIAlertController(title: "Error", message: "Cannot open camera roll.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
alertVC.addAction(okAction)
presentViewController(alertVC, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
imageView.contentMode = .ScaleAspectFit //3
imageView.image = chosenImage //4
dismissViewControllerAnimated(true, completion: nil) //5
}
func noCamera(){
let alertVC = UIAlertController(title: "No Camera", message: "Sorry, this device has no camera", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
alertVC.addAction(okAction)
presentViewController(alertVC, animated: true, completion: nil)
}
func savedImageAlert()
{
var alert:UIAlertView = UIAlertView()
alert.title = "Saved!"
alert.message = "Your picture was saved"
alert.delegate = self
alert.addButtonWithTitle("Ok")
alert.show()
}
}

Resources