swift 头像上传(3)头像保存与读取

前端之家收集整理的这篇文章主要介绍了swift 头像上传(3)头像保存与读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考:

头像保存:

http://blog.csdn.net/codingfire/article/details/51943286

http://www.cnblogs.com/linxiu-0925/p/5885638.html

头像获取显示参考

http://blog.csdn.net/CodingFire/article/details/52128773


//把选择的头像保存到本地
    func saveImage(image:UIImage)->String{
        //修正图片的位置
        //下面一句代码报错,暂时没有找到解决方法,以后有时间再弄吧
        //let image = fixOrientation((info[UIImagePickerControllerOriginalImage] as! UIImage))
        
        
        //先把图片转成NSData
        
        let data = UIImageJPEGRepresentation(image,0.5)
        //显示图片
        //self.imageview.image = UIImage(data: data!)
        
        //图片保存的路径
        
        //这里将图片放在沙盒的documents文件夹中
        
        
        
        //Home目录
        
        let homeDirectory = NSHomeDirectory()
        
        let documentPath = homeDirectory + "/Documents"
        
        //文件管理器
        
        let fileManager: NSFileManager = NSFileManager.defaultManager()
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        
        do {
            
            try fileManager.createDirectoryAtPath(documentPath,withIntermediateDirectories: true,attributes: nil)
            
        }
            
        catch _ {
            
        }
        
        
        
        fileManager.createFileAtPath(documentPath.stringByAppendingString("/image.png"),contents: data,attributes: nil)
        
        //得到选择后沙盒中图片的完整路径
        
        let filePath: String = String(format: "%@%@",documentPath,"/image.png")
        
       // print("filePath:" + filePath)
       return filePath
    }



使用方法
 //添加代理方法,用于执行图片拾取完成后的代码
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //判断是否允许裁剪
        if(picker.allowsEditing){
            //裁剪后图片
            let image = info["UIImagePickerControllerEditedImage"]as? UIImage
           // self.imageview.image = image
             let type: String = (info[UIImagePickerControllerMediaType] as! String)
            print(type)
            let imagePath:String = saveImage(image!)
            
            //根据保存路径获取显示图片
            let lastData = NSData(contentsOfFile: imagePath)
            self.imageview.image = UIImage(data: lastData!)
        }else{
            //原始图片
            let image = info["UIImagePickerControllerOriginalImage"]as? UIImage
            //self.imageview.image = image
            let type: String = (info[UIImagePickerControllerMediaType] as! String)
            print(type)
            let imagePath:String = saveImage(image!)
            
            //根据路径获取图片显示
            let lastData = NSData(contentsOfFile: imagePath)
            
            self.imageview.image = UIImage(data: lastData!)
            
        }
        
        self.dismissViewControllerAnimated(true,completion: nil )
    
    }
原文链接:https://www.f2er.com/swift/322996.html

猜你在找的Swift相关文章