简体   繁体   English

将从库中获取的图像设置为UIImageView

[英]Setting the image taken from the gallery to the UIImageView

The problem am facing is placing the picture i choose from the gallery into the UIImageView (imageChosen). 面临的问题是将我从图库中选择的图片放入UIImageView (imageChosen)。

The code runs fine without any errors but the picture i chose is not set to the "imageChosen" 代码运行正常没有任何错误,但我选择的图片没有设置为“imageChosen”

here is my code 这是我的代码

class postChoices: UIViewController {

    @IBOutlet weak var imageChosen: UIImageView!

    @IBAction func gallery(sender: AnyObject) {

        var image = UIImagePickerController()
        //image.delegate = self
        image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        image.allowsEditing = false

        self.presentViewController(image, animated: true, completion: nil)

    }
    override func viewDidLoad() {
        super.viewDidLoad()

            // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image2: UIImageView!, editingInfo: NSDictionary!) {
      //  let selectedImage : UIImageView = image
        imageChosen.image = image2.image

    }


}
//Complete solution with delegates and image handling    

     import UIKit

        class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

            @IBOutlet weak var myImageView: UIImageView!
            let picker = UIImagePickerController()

            @IBAction func gallery(sender: AnyObject) {

                if UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary) != nil {
                    picker.allowsEditing = false
                    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    presentViewController(picker, animated: true, completion: nil)
                } else {
                    noCamera()
                }

            }
            func noCamera(){
                let alertVC = UIAlertController(title: "No Camera", message: "Sorry, Gallery is not accessible.", preferredStyle: .Alert)
                let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
                alertVC.addAction(okAction)
                presentViewController(alertVC, animated: true, completion: nil)
            }

            override func viewDidLoad() {
                super.viewDidLoad()
                // Do any additional setup after loading the view, typically from a nib.
                picker.delegate = self   //the required delegate to get a photo back to the app.
             }

            //MARK: - Delegates
            //What to do when the picker returns with a photo
            func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
                var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
                myImageView.contentMode = .ScaleAspectFit //3
                myImageView.image = chosenImage //4
                dismissViewControllerAnimated(true, completion: nil) //5
            }
            //What to do if the image picker cancels.
            func imagePickerControllerDidCancel(picker: UIImagePickerController) {
                dismissViewControllerAnimated(true, completion: nil)
            }
        }

Demo Project 演示项目

Several problems. 几个问题。

If you look at the docs the method imagePickerController:didFinishPickingImage:editingInfo: was deprecated in iOS 3.0 . 如果您查看文档,方法imagePickerController:didFinishPickingImage:editingInfo:在iOS 3.0中已弃用。

It's a fair bet it's not even being called. 这是一个公平的赌注,甚至没有被召唤。 (You have the line that sets up your view controller as the delegate commented out, so the image picker won't call your delegate methods. (您有一个设置视图控制器的行作为委托注释掉,因此图像选择器不会调用您的委托方法。

In your imagePickerController:didFinishPickingImage:editingInfo: method you have image2 defined as a UIImageView. 在你的imagePickerController:didFinishPickingImage:editingInfo:你将image2定义为UIImageView的方法。 It's not, it's a UIImage. 它不是,它是一个UIImage。

You should un-comment the line image.delegate = self . 你应该取消注释image.delegate = self

You should implement the method imagePickerController:didFinishPickingMediaWithInfo: instead of imagePickerController:didFinishPickingImage:editingInfo: . 你应该实现方法imagePickerController:didFinishPickingMediaWithInfo:而不是imagePickerController:didFinishPickingImage:editingInfo: .

You probably also need to add UIImagePickerControllerDelegate to the definition of your view controller class so the compiler knows that your view controller conforms to the UIImagePickerControllerDelegate protocol. 您可能还需要将UIImagePickerControllerDelegate添加到视图控制器类的定义中,以便编译器知道您的视图控制器符合UIImagePickerControllerDelegate协议。

    - (void) makeUIImagePickerControllerForCamera:(BOOL)camera {

         UIImagePickerController *picker = [[UIImagePickerController alloc] init];
         picker.delegate = self;
         picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

         [picker setMediaTypes:[NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil]];

         [self presentModalViewController: picker animated: YES];
    }

    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        // Dismiss the picker
        [[picker parentViewController] dismissModalViewControllerAnimated:YES];

    // Get the image from the result
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"];

    myUIImage.image = image;
}

This code helped me with swift 3.0 这段代码帮助我使用swift 3.0

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        billImageView.contentMode = .scaleAspectFill
        billImageView.image = pickedImage
    }
    self.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    self.dismiss(animated: true, completion: nil)
}

In Swift 3.0 in this code you have select both option camera and Gallary 在此代码中的Swift 3.0中,您可以选择选项摄像头和Gallary

import UIKit
import Foundation
import AVFoundation
class HostVC: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{    
@IBOutlet weak var imgHostProfile:UIImageView!
    let captureSession = AVCaptureSession()
    let stillImageOutput = AVCaptureStillImageOutput()
    var previewLayer : AVCaptureVideoPreviewLayer?
    var captureDevice : AVCaptureDevice?

 @IBAction func btnChangeprofileTapped(_ sender: UIButton)
    {


        DispatchQueue.main.async
            {
                let alert = UIAlertController(title: "Alert", message: "Choose profile picture from Camera or Gallery", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Take a photo", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
                    DispatchQueue.main.async
                        {
                            if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) ==  AVAuthorizationStatus.authorized {
                                self.Cemara()
                            } else {
                                AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
                                    if granted == true {
                                        self.Cemara()
                                    } else {
                                        self.showalert(strMessage: Validation.kCameraAccess)
                                    }
                                })
                            }

                    }
                }))
                alert.addAction(UIAlertAction(title: "Choose from Library", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
                    DispatchQueue.main.async
                        {
                            let imagepicker = UIImagePickerController()
                            imagepicker.delegate = self
                            imagepicker.sourceType = .photoLibrary

                            self.present(imagepicker, animated: true, completion: nil)
                    }
                }))

                alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in}))

                self.present(alert, animated: true, completion: nil)

        }


    }

    func Cemara()
    {
        DispatchQueue.main.async {
            if UIImagePickerController.availableCaptureModes(for: .rear) != nil
            {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.sourceType = .camera
                self.present(imagePicker, animated: true, completion: nil)
            }
            else
            {
                self.noCamera()
            }
        }
    }

    //======================================================================
    //                  MARK: -  Camera  Code
    //======================================================================

    func noCamera()
    {
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice]
        {
            for device in devices
            {
                if (device.hasMediaType(AVMediaTypeVideo))
                {
                    if(device.position == AVCaptureDevicePosition.front)
                    {
                        captureDevice = device
                        if captureDevice != nil
                        {
                            print("Capture device found")
                            beginSession()
                        }
                    }
                }
            }
        }
    }

    //======================================================================
    //                  MARK: - Camera Capture Start Session Code Here
    //======================================================================

    func beginSession()
    {
        do
        {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            if captureSession.canAddOutput(stillImageOutput)
            {
                captureSession.addOutput(stillImageOutput)
            }
        }
        catch
        {
            print("error: \(error.localizedDescription)")
        }
        guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else
        {
            print("no preview layer")
            return
        }
        self.view.layer.addSublayer(previewLayer)
        previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()
        self.view.addSubview(imgHostProfile)


    }

    //======================================================================
    //                  MARK: - Gallary Code
    //======================================================================

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {
        if let imagedata = info[UIImagePickerControllerOriginalImage] as? UIImage
        {
            self.imgHostProfile.image = imagedata
            print(imagedata)


        }

        dismiss(animated: true, completion: nil)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM