"创建具有未知类型的图像格式是错误"使用UIImagePickerController

时间:2016-08-18 04:14:09

标签: ios swift xcode uiimageview xcode8

从iOS 10 Swift 3中的图像选择器中选择图像时出现错误 - Creating an image format with an unknown type is an error

 func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    imagePost.image = image
    self.dismiss(animated: true, completion: nil)
}

未选择并更新图像。我需要帮助或建议才能知道在iOS10或Swift 3中是否更改了此方法的语法或任何内容,或者是否有其他方法可以执行此操作。

23 个答案:

答案 0 :(得分:28)

下面提到的代码确实解决了我的问题 -

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imagePost.image = image
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)
}

答案 1 :(得分:11)

请记住将委托添加到自己

let picker = UIImagePickerController()
picker.delegate = self // delegate added

答案 2 :(得分:10)

下面的代码确实解决了问题:

如果用户对所选图像执行更改,则仅拉动该图像,否则无需任何更改即可拉动原始图像源,最后取消图像选取器视图控制器。

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
        imageView.image = image
    }
    else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.image = image
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)
}

答案 3 :(得分:7)

如果您允许编辑图片imageController.allowsEditing = true,则需要先获取已编辑的图片:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    picker.dismissViewControllerAnimated(true, completion: nil)

    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
        imagePost.image = image
    } else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imagePost.image = image
    } else {
        imagePost.image = nil
    }
}

答案 4 :(得分:5)

accepted solution Jeetendra Choudhary有效。虽然在Xcode 8中使用Swift 3,我注意到它会生成警告: Instance method 'imagePickerController(_:didFinishPickingMediaWithInfo:)' nearly matches optional requirement 'imagePickerController(_:didFinishPickingMediaWithInfo:)' of protocol 'UIImagePickerControllerDelegate'

enter image description here

并建议添加 @nonobjc 私有关键字以消除警告。如果您使用这些建议使警告静音,则解决方案不再有效。

答案 5 :(得分:5)

我发现照片库中的默认图像可以解决这个问题。 如果将图像从计算机拖动到模拟器上并选择它。 这个问题解决了

答案 6 :(得分:3)

根据Abdurohman的回答,我改变了我的代码并解决了问题,谢谢。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    photoImageView.image = selectedImage

    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}

答案 7 :(得分:2)

将此添加到viewDidload()

imagepicker.delegate = self

答案 8 :(得分:1)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imgViewPhoto.image = image
    } else{
        print("Something went wrong")
    }

    picker.dismiss(animated: true, completion: nil)

}

答案 9 :(得分:1)

我认为你错过了photoImageView和图片之间的联系。

看看下面的截图:

enter image description here

enter image description here

答案 10 :(得分:1)

对于带有swift 3的Xcode 8.1,在更改委托方法后如下

改变你的

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    imagePost.image = image
    self.dismiss(animated: true, completion: nil)
}

功能

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

    {


imagePost.image = info[UIImagePickerControllerOriginalImage] as? UIImage
 picker.dismiss(animated: true, completion: nil)

}

我忘了将UINavigationControllerDelegate和UIImagePickerControllerDelegate一起添加到

class ViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate

你会在开头添加一个变量,如

var imagePicker = UIImagePickerController()

并设置委托并将viewdidload()中的函数调用为

 imagePicker.delegate = self
 viwImagePick()

然后将该功能解释为

  //ImagePicker
    func viwImagePick(){


        let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.alert)

        alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
            print("Camera selected")
            self.openCamera()

            //Code for Camera
            //cameraf
        })
        alert.addAction(UIAlertAction(title: "Photo library", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
            print("Photo selected")
            self.openGallary()

            //Code for Photo library
            //photolibaryss
        })


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



    func openCamera()
    {
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        if UIDevice.current.userInterfaceIdiom == .phone
        {
            self.present(imagePicker, animated: true, completion: nil)
        }
        else
        {
            let popover = UIPopoverController(contentViewController: imagePicker)

            popover.present(from: profileImgViw.frame, in: self.view, permittedArrowDirections: UIPopoverArrowDirection.any, animated: true)

        }
    }

    func openGallary()
    {
        imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
        if UIDevice.current.userInterfaceIdiom == .phone
        {
            self.present(imagePicker, animated: true, completion: nil)
        }
        else
        {
           let popover = UIPopoverController(contentViewController: imagePicker)

            popover.present(from: profileImgViw.frame, in: self.view, permittedArrowDirections: UIPopoverArrowDirection.any, animated: true)


        }
    }

现在图像已添加到库中的图像视图

答案 11 :(得分:1)

我认为你错过了photoImageView和图片之间的联系。

看看下面的截图:

enter image description here

enter image description here

祝你好运!

答案 12 :(得分:1)

更改didFinishPickingMediaWithInfo info: [String : AnyObject],  到didFinishPickingMediaWithInfo info: [String : Any]

答案 13 :(得分:1)

public function filterKomoditi(Request $request){
        $kblicodes = Kblicode::groupBy('kblicode')->lists('kblicode', 'kblicode');

        // mengambil parameter
        $getkbli = $request->get('kbli');
        $gettahun = $request->get('tahun');
        $getnegara = $request->get('negara');
        $getpelabuhan = $request->get('pelabuhan');

        if($getkbli!=null){
            $hscode = Kblicode::where('kblicode', $getkbli)->get();
        }

        // fungsi select import where multiple hscode
        $condition = array();
            foreach ($hscode as $hs) {
                array_push($condition, $hs->hscode);
            }

        // fungsi filter
        if($gettahun != null && $getnegara != null && $getpelabuhan !=null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_negara', $getnegara)->whereIn('kode_pelabuhan', $getpelabuhan);
            $exports = Export::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_negara', $getnegara)->whereIn('kode_pelabuhan', $getpelabuhan);
        }elseif($gettahun != null && $getnegara == null && $getpelabuhan ==null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('tahun', $gettahun);
            $exports = Export::whereIn('hscode', $condition)->whereIn('tahun', $gettahun);
        }elseif($gettahun == null && $getnegara != null && $getpelabuhan ==null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('kode_negara', $getnegara);
            $exports = Export::whereIn('hscode', $condition)->whereIn('kode_negara', $getnegara);    
        }elseif($gettahun == null && $getnegara == null && $getpelabuhan !=null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('kode_pelabuhan', $getpelabuhan);
            $exports = Export::whereIn('hscode', $condition)->whereIn('kode_pelabuhan', $getpelabuhan);
        }elseif($gettahun == null && $getnegara == null && $getpelabuhan ==null){
            $imports = Import::whereIn('hscode', $condition);
            $exports = Export::whereIn('hscode', $condition);    
        }elseif($gettahun != null && $getnegara != null && $getpelabuhan ==null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_negara', $getnegara);
            $exports = Export::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_negara', $getnegara);    
        }elseif($gettahun != null && $getnegara == null && $getpelabuhan !=null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_pelabuhan', $getpelabuhan);
            $exports = Export::whereIn('hscode', $condition)->whereIn('tahun', $gettahun)->whereIn('kode_pelabuhan', $getpelabuhan);    
        }elseif($gettahun == null && $getnegara != null && $getpelabuhan !=null){
            $imports = Import::whereIn('hscode', $condition)->whereIn('kode_negara', $getnegara)->whereIn('kode_pelabuhan', $getpelabuhan);
            $exports = Export::whereIn('hscode', $condition)->whereIn('kode_negara', $getnegara)->whereIn('kode_pelabuhan', $getpelabuhan);    
        }

        // fungsi select tahun negara, dan pelabuhan dari data Import
        $import_tahun_all = Import::whereIn('hscode', $condition)->groupBy('tahun')->get();
        $import_negara_all = Import::whereIn('hscode', $condition)->groupBy('nama_negara')->get();
        $import_pelabuhan_all = Import::whereIn('hscode', $condition)->groupBy('nama_pelabuhan')->get();

        // fungsi select tahun dan negara dari data export
        $export_tahun_all = Export::whereIn('hscode', $condition)->groupBy('tahun')->get();
        $export_negara_all = Export::whereIn('hscode', $condition)->groupBy('nama_negara')->get();
        $export_pelabuhan_all = Export::whereIn('hscode', $condition)->groupBy('nama_pelabuhan')->get();

        //tahun array
        $tahun_array = array();            
            foreach ($import_tahun_all as $import_tahun){
                if(!in_array($import_tahun->tahun, $tahun_array)){
                    array_push($tahun_array, $import_tahun->tahun);
                }
            }
            foreach ($export_tahun_all as $export_tahun){
                if(!in_array($export_tahun->tahun, $tahun_array)){
                    array_push($tahun_array, $export_tahun->tahun);
                }
            }
        sort($tahun_array);

        // negara array with key => value. 
          $negaraArray = [];
          foreach ($import_negara_all as $import_negara){
              if(!array_key_exists($import_negara->nama_negara, $negaraArray)){
                  $negaraArray = array_add($negaraArray, $import_negara->nama_negara, $import_negara->kode_negara);
              }
          }
          foreach ($export_negara_all as $export_negara){
              if(!array_key_exists($export_negara->nama_negara, $negaraArray)){
                  $negaraArray = array_add($negaraArray, $export_negara->nama_negara, $export_negara->kode_negara);
              }
          }
        ksort($negaraArray);

        // pelabuhanArray with key => value
        $pelabuhanArray = [];
        foreach ($import_pelabuhan_all as $import_pelabuhan){
              if(!array_key_exists($import_pelabuhan->nama_pelabuhan, $pelabuhanArray)){
                  $pelabuhanArray = array_add($pelabuhanArray, $import_pelabuhan->nama_pelabuhan, $import_pelabuhan->kode_pelabuhan);
              }
          }
          foreach ($export_pelabuhan_all as $export_pelabuhan){
              if(!array_key_exists($export_pelabuhan->nama_pelabuhan, $pelabuhanArray)){
                  $pelabuhanArray = array_add($pelabuhanArray, $export_pelabuhan->nama_pelabuhan, $export_pelabuhan->kode_pelabuhan);
              }
          }
          ksort($pelabuhanArray);


        // paginate
        $imports = $imports->paginate();
        $exports = $exports->paginate();

        // fungsi sum berat bersih dan nilai
        $neto_import = $imports->sum('berat_bersih');
        $value_import = $imports->sum('nilai');
        $neto_export = $exports->sum('berat_bersih');
        $value_export = $exports->sum('nilai');

        return view('pages.filter', compact('kblicodes', 'getkbli', 'imports', 'neto_import', 'value_import', 'import_tahun_all', 'import_negara_all', 'exports', 'export_tahun_all', 'export_negara_all', 'neto_export', 'value_export', 'tahun_array', 'negaraArray', 'pelabuhanArray', 'gettahun', 'getnegara','getpelabuhan')); 
}

答案 14 :(得分:1)

如果这对任何人都有帮助,那么当我将UIImageView子类化以创建圆角视图时,我就会发生这种情况。当我在viewDidLoad()

中添加以下行时也会发生这种情况
imageView.layer.cornerRadius = self.imageView.frame.size.width / 2

我最终在viewWillLayoutSubViews中添加了这行,并且它有效。有关详细信息,请参阅此处:

clipsToBounds causes UIImage to not display in iOS10 & XCode 8

答案 15 :(得分:1)

这对我有用:

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

答案 16 :(得分:1)

在函数参数中添加“_”。

func imagePickerController(picker: UIImagePickerController ...

func imagePickerController(_ picker: UIImagePickerController ...

答案 17 :(得分:0)

//带有集合视图的图像选择器 class ViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate {

@IBOutlet var img: UIImageView!

@IBOutlet weak var collview: UICollectionView!

var image = NSMutableArray()


let imgpkr = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    imgpkr.delegate = self
}




@IBAction func btnselect(_ sender: UIButton) {


    imgpkr.allowsEditing = true // false
    imgpkr.sourceType = .photoLibrary
    imgpkr.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
    present(imgpkr, animated: true, completion: nil)

}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let choose = info[UIImagePickerControllerOriginalImage]as!UIImage
    let edit = info[UIImagePickerControllerEditedImage]as!UIImage

    img.contentMode = .scaleAspectFit
    img.image = edit

    //MARK:- Add image in collview

    image.add(edit)
    collview.reloadData()

    dismiss(animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

    dismiss(animated: true, completion: nil)
}

//MARK:- Collection View


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return image.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collview.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)as! CollectionViewCell1

    cell.img1.image = image.object(at: indexPath.item)as! UIImage

    return cell



}

答案 18 :(得分:0)

尝试以下

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print("image selected");
    let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImag
    self.dismiss(animated: true, completion: nil)
   UIImg.image = selectedImage
}

答案 19 :(得分:0)

我做的是,一旦我从didFinishPickingMediaWithInfo获得图像,我就打电话给:

func prepareImageForSaving(image:UIImage) {
    // create NSData from UIImage
    guard let imageData = UIImageJPEGRepresentation(image, 1) else {
        // handle failed conversion
        print("jpg error")
        return
    }

    self.saveImage(imageData: imageData as NSData)
}

func saveImage(imageData: NSData) {
    imageDatas = imageData
}

以NSData格式保存。

控制台仍警告我" [Generic]创建一个未知类型的图像格式是一个错误"但至少我的imageView会更新到所选图像,而不是从viewDidLoad显示前一个图像。

答案 20 :(得分:0)

这对我有用。 只需复制并粘贴即可。

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // The info dictionary contains multiple representations of the image, and this uses the original.
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    // Set photoImageView to display the selected image.
     photoImageView.image = selectedImage

    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}

答案 21 :(得分:0)

请务必同时包含UINavigationControllerDelegate代表。这解决了我的问题。

答案 22 :(得分:-1)

对我来说,我遇到了错误:

  

“致命错误:意外发现零...”

在图像选择器中选择图像时。

为解决该问题,我再次创建了imageView的插座。