一句话选择单个头像图片

新建ImagePickerViewController类:

/* let imagePicker = ImagePickerViewController()

imagePicker.delegate = self

self.presentViewController(imagePicker, animated: false, completion: nil)

*/

实现类代理方法

//MARK: -ImagePickerViewDelegate

extension FourViewController:ImagePickerViewDelegate{

func getImage(image: UIImage) {

headView?.headImage?.image = image

}

}

ImagePickerViewController类中实现代码

import UIKit

import AVFoundation

import MobileCoreServices

protocol ImagePickerViewDelegate {

func getImage(image:UIImage)

}

class ImagePickerViewController: UIViewController,UIActionSheetDelegate {

var delegate:ImagePickerViewDelegate?

var alertController:UIAlertController?

var pickCtr:UIImagePickerController?

init(){

super.init(nibName: nil, bundle: nil)

self.modalPresentationStyle = .OverFullScreen

self.view.backgroundColor = UIColor.clearColor()

pickCtr = UIImagePickerController()

pickCtr!.delegate = self;

pickCtr!.allowsEditing = true;

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

override func viewDidAppear(animated: Bool) {

super.viewDidAppear(animated)

if (alertController == nil) {

alertController = UIAlertController(title: "选择文件源", message: nil, preferredStyle: .ActionSheet)

alertController?.addAction(UIAlertAction(title: "打开相机", style: .Default, handler: { (action) in

self.takePhoto()

}))

alertController?.addAction(UIAlertAction(title: "打开相册", style: .Default, handler: { (action) in

self.localPhoto()

}))

alertController?.addAction(UIAlertAction(title: "取消", style: .Default, handler: { (action) in

self.dismissViewControllerAnimated(false, completion: nil)

}))

self.presentViewController(alertController!, animated: true, completion: nil)

}

}

/// 打开相册

func localPhoto(){

if (self.isPhotoLibraryAvailable()){

pickCtr?.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

self.presentViewController(pickCtr!, animated: true, completion: nil)

}else{

let alert = UIAlertController(title: nil, message: "相册不可用", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

self.dismissViewControllerAnimated(false, completion: nil)

}))

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

}

}

/// 打开相机takePhoto

func takePhoto(){

let mediaType = AVMediaTypeVideo

let authStatus = AVCaptureDevice.authorizationStatusForMediaType(mediaType)

let you = self.isCameraAvailable()==true

let my = self.doesCameraSupportTakingPhotos()==true

pprintLog("you:\(you)")

pprintLog("my:\(my)")

pprintLog("myandyou:\(my&&you)")

if(authStatus == AVAuthorizationStatus.Restricted || authStatus == AVAuthorizationStatus.Denied){

let alert = UIAlertController(title: nil, message: "相机不可用,请到系统设置里更改", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

self.dismissViewControllerAnimated(false, completion: nil)

}))

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

}else if(self.isCameraAvailable()==true && self.doesCameraSupportTakingPhotos()==true){

pickCtr!.sourceType = UIImagePickerControllerSourceType.Camera

self.presentViewController(pickCtr!, animated: true, completion: nil)

}else{

let alert = UIAlertController(title: nil, message: "相机不可用", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

self.dismissViewControllerAnimated(false, completion: nil)

}))

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

}

}

override func viewDidLoad() {

super.viewDidLoad()

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

//MARK: - UIImagePickerControllerDelegate

extension ImagePickerViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

//取消

func imagePickerControllerDidCancel(picker: UIImagePickerController) {

pickCtr?.dismissViewControllerAnimated(true, completion: {

self.dismissViewControllerAnimated(false, completion: nil)

})

}

// 得到图片

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

let type:String = info[UIImagePickerControllerMediaType] as! String

if (type == kUTTypeImage as String){

let img:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage

//对拍照后的照片进行处理

let image1 = self.fixOrientationIm(img)

//防止图片翻滚

let image2 = self.fixOrientationIm(image1)

//改变图片的size

let image3 = self.image(image2, targetSize: CGSizeMake(110, 80))

pickCtr?.dismissViewControllerAnimated(true, completion: {

self.dismissViewControllerAnimated(false, completion: {

self.delegate?.getImage(image3)

})

})

}

}

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

}

}

/// 判断手机是否支持。。相机....

extension ImagePickerViewController{

/// 判断设备是否有摄像头

func isCameraAvailable()->Bool{

return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)

}

/// 后面的摄像头是否可用

func isRearCameraAvailable()->Bool{

return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear)

}

/// 前面的摄像头是否可用

func isFrontCameraAvailable()->Bool{

return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)

}

/// 相册是否可用

func isPhotoLibraryAvailable()->Bool{

return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)

}

/// 相机是否可以取到图片

func doesCameraSupportTakingPhotos()->Bool{

return self.cameraSupportsMedia( kUTTypeImage as String, paramSourceType: UIImagePickerControllerSourceType.Camera)

}

/// 相机是否可以取到视频

func doesCameraSupportTakingVideos()->Bool{

return self.cameraSupportsMedia( kUTTypeMovie as String, paramSourceType: UIImagePickerControllerSourceType.Camera)

}

/// 相册是否可以取到视频

func canUserPickVideosFromPhotoLibrary()->Bool{

return self.cameraSupportsMedia(kUTTypeMovie as String, paramSourceType: UIImagePickerControllerSourceType.PhotoLibrary)

}

/// 相册是否可以取到图片

func canUserPickPhotosFromPhotoLibrary()->Bool{

return self.cameraSupportsMedia(kUTTypeImage as String, paramSourceType: UIImagePickerControllerSourceType.PhotoLibrary)

}

func cameraSupportsMedia(paramMediaType:String,paramSourceType:UIImagePickerControllerSourceType)->Bool{

var result = false

if paramMediaType.characters.count==0{

return false

}

let availableMediaTypes:NSArray? = UIImagePickerController.availableMediaTypesForSourceType(paramSourceType)

if availableMediaTypes != nil{

availableMediaTypes!.enumerateObjectsUsingBlock { (obj, idx,stop) in

let mediaType:String = obj as! String

if mediaType == paramMediaType{

result = true

//        stop = true;

}

}

}

return result;

}

}

//MARK: - 图片方法

extension ImagePickerViewController{

//MARK:- 相机照片处理

func fixOrientationIm(aImage:UIImage) -> UIImage{

// No-op if the orientation is already correct

if (aImage.imageOrientation == UIImageOrientation.Up){

return aImage

}

// We need to calculate the proper transformation to make the image upright.

// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.

var transform  = CGAffineTransformIdentity

switch (aImage.imageOrientation) {

case UIImageOrientation.Down:

break

case UIImageOrientation.DownMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);

transform = CGAffineTransformRotate(transform, CGFloat(M_PI));

break

case UIImageOrientation.Left:

break

case UIImageOrientation.LeftMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));

break

case UIImageOrientation.Right:

break

case UIImageOrientation.RightMirrored:

transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);

transform = CGAffineTransformRotate(transform, -CGFloat(M_PI_2));

break

default:

break

}

switch (aImage.imageOrientation) {

case UIImageOrientation.UpMirrored:

break

case UIImageOrientation.DownMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

transform = CGAffineTransformScale(transform, -1, 1);

break

case UIImageOrientation.LeftMirrored:

break

case UIImageOrientation.RightMirrored:

transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);

transform = CGAffineTransformScale(transform, -1, 1);

break

default:

break

}

// Now we draw the underlying CGImage into a new context, applying the transform

// calculated above.

let ctx:CGContextRef = CGBitmapContextCreate(nil, Int(aImage.size.width), Int(aImage.size.height), CGImageGetBitsPerComponent(aImage.CGImage!), 0, CGImageGetColorSpace(aImage.CGImage!)!, CGImageGetBitmapInfo(aImage.CGImage!).rawValue)!

CGContextConcatCTM(ctx, transform);

switch (aImage.imageOrientation) {

case UIImageOrientation.Left:

break

case UIImageOrientation.LeftMirrored:

break

case UIImageOrientation.Right:

break

case UIImageOrientation.RightMirrored:

// Grr...

CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage!);

break

default:

CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage!);

break

}

// And now we just create a new UIImage from the drawing context

let cgimg = CGBitmapContextCreateImage(ctx)

let img = UIImage(CGImage: cgimg!)

//        CGContextRelease(ctx)

//        CGImageRelease(cgimg)

return img;

}

/// 裁剪图片

func image(image:UIImage,targetSize:CGSize)-> UIImage{

UIGraphicsBeginImageContext(targetSize)

image.drawInRect(CGRectMake(0, 0, targetSize.width, targetSize.height))

let newImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

return newImage!

}

///得到图片

func getImageWithName(iName:String)->UIImage{

let cloudIcon = UIImage(contentsOfFile: self.cachedPicPath(iName))

return cloudIcon!

}

/// 存储图片

func saveImage(image:UIImage,name:String){

UIImagePNGRepresentation(image)?.writeToFile(name, atomically: true)

}

/// 获取图片路径

func cachedPicPath(imageN:String)->String{

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask.UserDomainMask, true)

let documentsPath:NSString = paths.first! as NSString

let imageName = imageN+".png"

let path = documentsPath.stringByAppendingPathComponent(imageName)

return path

}

}

swift 2 选择头像图片的更多相关文章

  1. 相册选择头像或者拍照 上传头像以NSData 图片二进制格式 表单上传

    一.点击头像图片 或者按钮 在相册选择照片返回img,网络上传头像要用data表单上传 (1)上传头像属性 // 图片二进制格式 表单上传 @property (nonatomic, strong) ...

  2. swift上传头像

    很久没有写博客了,今天特地写了这个,也是一边仿照别人写的demo,注释部分都是需要的.需要的同学可以参考一下. @IBAction func headImageBtnPage(){  //上传头像 / ...

  3. Android中调用另一个Activity并返回结果-以模拟选择头像功能为例

    场景 Android中点击按钮启动另一个Activity以及Activity之间传值: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detail ...

  4. ajax实现注册并选择头像后上传

    在初次接触ajax后,我们做了一个crm训练的项目,大多数小组都有注册用户这一项,但是都忽略掉了一个功能,那就是,很多网站的注册是可以上传头像的,在这里我做了一个在已有的头像数组里选择图片上传作头像的 ...

  5. php使用post动态选择头像和js事件动态改变头像

    <html> <head> <meta http-equit="Content-type" content="text/html" ...

  6. jQuery滑过头像图片展示个人信息效果

    这是一款经典的jQuery图片插件,同时,也可以是一款jQuery提示框插件.这款jQuery插件的功能是当你把鼠标滑过头像图片缩略图时,即可弹出头像对应用户的详细个人信息,弹出的标签虽然不大,但是还 ...

  7. Android选择头像

    http://www.jianshu.com/p/8b3e78046c1c 注意:在Android6.0之后,使用相机拍照需要权限 在选择头像使用相机拍摄时添加以下代码即可. Acp.getInsta ...

  8. Android实战简易教程-第二十八枪(基于Bmob实现头像图片设置和网络上传功能!)

    上一篇我们介绍了怎样由uri转换成String ,本文就用到了上篇文章的方法.以下我们介绍一下怎样设置头像后将头像图片上传到云端的方法,本文基于Bmob提供的服务. 看一下代码:(布局文件和前两篇文章 ...

  9. 「小程序JAVA实战」小程序头像图片上传(下)(45)

    转自:https://idig8.com/2018/09/09/xiaochengxujavashizhanxiaochengxutouxiangtupianshangchuan44/ 接下来,我们应 ...

随机推荐

  1. SQL查询表的行列转换/小计/统计(with rollup,with cube,pivot解析)

    SQL查询表的行列转换/小计/统计(with rollup,with cube,pivot解析) 2013-8-20 1.    SQL查询表的行列转换/小计/统计(with  rollup,with ...

  2. Java笔记:内部类

    1.把一个类放在另一类内部定义,这个定义在其他类里面的类就叫做内部类,包含内部类的类叫做外部类.内部类成员可以直接访问外部类的私有数据,但是外部类不能访问内部类的实现细节. 2.非静态内部类(没有st ...

  3. javac命令

    javac命令 javac命令初窥 注:以下红色标记的参数在下文中有所讲解. 用法: javac <options> <source files> 其中, 可能的选项包括:   ...

  4. 一步一步深入spring(2)-三种方式来实例化bean

    在一步一步深入spring(1)--搭建和测试spring的开发环境中提到了一种实例化bean的方式,也是最基本的使用构造器实例化bean 1.使用构造器实例化bean:这是最简单的方式,Spring ...

  5. kinect (oldest one) (libfreenect with py_kinect) on linux ubuntu14.04 x64

    freenect libs Where is the resource? Here :P : https://github.com/OpenKinect/libfreenect To make sur ...

  6. Archives for the category: Fisheye/Crucible

    Archives for the category: Fisheye/Crucible Introducing FishEye and Crucible 3.0 – Search, visualize ...

  7. Using django model/authentication/authorization within Tornado

    There is a project which is deployed within django. So its authentication system is built from Djang ...

  8. linuxmint 15/ ubuntu 13.04 install OpenERP client 6.0.4

    As we all know OpenERP is a great open-source ERP/CRM project. It does help people a lot when workin ...

  9. Hackers’ Crackdown-----UVA11825-----DP+状态压缩

    题目地址:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  10. Servlet部署描述文件(web.xml)

    最近看了下配置文件(Deployment Descriptor:简称DD),又称部署描述文件,下面详细介绍下该文件的组成和作用: 一.<web-app>有四个属性: 1.xmlns:申明了 ...