swift 2 选择头像图片

一句话选择单个头像图片
新建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 选择头像图片的更多相关文章
- 相册选择头像或者拍照 上传头像以NSData 图片二进制格式 表单上传
一.点击头像图片 或者按钮 在相册选择照片返回img,网络上传头像要用data表单上传 (1)上传头像属性 // 图片二进制格式 表单上传 @property (nonatomic, strong) ...
- swift上传头像
很久没有写博客了,今天特地写了这个,也是一边仿照别人写的demo,注释部分都是需要的.需要的同学可以参考一下. @IBAction func headImageBtnPage(){ //上传头像 / ...
- Android中调用另一个Activity并返回结果-以模拟选择头像功能为例
场景 Android中点击按钮启动另一个Activity以及Activity之间传值: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detail ...
- ajax实现注册并选择头像后上传
在初次接触ajax后,我们做了一个crm训练的项目,大多数小组都有注册用户这一项,但是都忽略掉了一个功能,那就是,很多网站的注册是可以上传头像的,在这里我做了一个在已有的头像数组里选择图片上传作头像的 ...
- php使用post动态选择头像和js事件动态改变头像
<html> <head> <meta http-equit="Content-type" content="text/html" ...
- jQuery滑过头像图片展示个人信息效果
这是一款经典的jQuery图片插件,同时,也可以是一款jQuery提示框插件.这款jQuery插件的功能是当你把鼠标滑过头像图片缩略图时,即可弹出头像对应用户的详细个人信息,弹出的标签虽然不大,但是还 ...
- Android选择头像
http://www.jianshu.com/p/8b3e78046c1c 注意:在Android6.0之后,使用相机拍照需要权限 在选择头像使用相机拍摄时添加以下代码即可. Acp.getInsta ...
- Android实战简易教程-第二十八枪(基于Bmob实现头像图片设置和网络上传功能!)
上一篇我们介绍了怎样由uri转换成String ,本文就用到了上篇文章的方法.以下我们介绍一下怎样设置头像后将头像图片上传到云端的方法,本文基于Bmob提供的服务. 看一下代码:(布局文件和前两篇文章 ...
- 「小程序JAVA实战」小程序头像图片上传(下)(45)
转自:https://idig8.com/2018/09/09/xiaochengxujavashizhanxiaochengxutouxiangtupianshangchuan44/ 接下来,我们应 ...
随机推荐
- 博客已迁移到lizhug.com
新的博客地址 http://lizhug.com
- Cygwin 各种情况下中文乱码--终极解决方案
0.引言 本人从进公司以来一直负责公司Android平台下产品的NDK开发,用的工具: 01. Google的adt-bundle(集成了eclipse和sdk) 02. NDK 03. Cygwin ...
- 调试设置移动端Web开发环境搭建实践
新手发帖,很多方面都是刚入门,有错误的地方请大家见谅,欢迎批评指正 本文重要总结一下挪动端进行前端开发时需要用到的一些工具,以及他们之间互相的组合,同时也包含本人应用的组合. 1. Chrome To ...
- java打印正金字塔,倒金字塔和“水影”金字塔
java打印正金字塔,倒金字塔和"水影"金字塔 --------原创文章,若要转载,请注明出处 小小少年 闲来无事,想起自己初学java的时候做的经典的无非就是打印出一些有意思 ...
- TCP报文中的SYN,FIN,ACK,PSH,RST,URG
TCP的三次握手是怎么进行的:发送端发送一个SYN=1,ACK=0标志的数据包给接收端,请求进行连接,这是第一次握手:接收端收到请求并且允许连接的话,就会发送一个SYN=1,ACK=1标志的数据包给发 ...
- AngularJS2之本地环境搭建
前言:本来准备初探AngularJS2,结果成了复习git和再探node git的两个常见问题:一.github上传时出现error: src refspec master does not matc ...
- Jquery datepicker 时间插件使用 js 时间相加,相减
$(document).ready(function(){ //输入框事件 $('#probation').bind('input propertychange', function() { var ...
- 第一百三十四节,JavaScript,封装库--遮罩锁屏
JavaScript,封装库--遮罩锁屏 封装库新增1个方法 /** zhe_zhao_suo_ping()方法,将一个区块元素设置成遮罩锁屏区块 * 注意:一般需要在css文件将元素设置成隐藏 ** ...
- 【Python】32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【LeetCode】23. Merge k Sorted Lists
合并k个已合并链表. 思路:先把链表两两合并,直到合并至只有一个链表 /** * Definition for singly-linked list. * struct ListNode { * in ...