你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> Swift 2.0圖片上傳以及圖片客戶端壓縮代碼

Swift 2.0圖片上傳以及圖片客戶端壓縮代碼

編輯:IOS7技巧
Swift 2.0圖片上傳功能我們用到的比較多特別是在ios中的app開發時會用到了,今天我們來給各位朋友介紹一個使用Swift 2.0圖片上傳的例子。


Swift 2.0圖片上傳以及圖片客戶端壓縮是寫某一個app中,抽離的,其實比較簡單,也沒有做很多的IOS內部機制判斷,只是實現了圖片上傳以及圖片壓縮後上傳的功能。


//
//  ViewController.swift
//  uploadImage
//
//  Created by jincon on 15/11/1.
//  Copyright © 2015年 jincon. All rights reserved.
//

import UIKit

class ViewController: UIViewController , UIImagePickerControllerDelegate,
UINavigationControllerDelegate {

    @IBOutlet weak var imageView: UIImageView!
   
    @IBAction func fromAlbum(sender: AnyObject) {
        //判斷設置是否支持圖片庫
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            //初始化圖片控制器
            let picker = UIImagePickerController()
            //設置代理
            picker.delegate = self
            //指定圖片控制器類型
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            //設置是否允許編輯
            //picker.allowsEditing = editSwitch.on
            //彈出控制器,顯示界面
            self.presentViewController(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            print("讀取相冊錯誤")
        }
       
       
    }
   
    //選擇圖片成功後代理
    func imagePickerController(picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [String : AnyObject]) {
            //查看info對象
            print(info)
            //獲取選擇的原圖
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            imageView.image = image
            let midImage:UIImage=self.imageWithImageSimple(image,scaledToSize:CGSizeMake(800.0,800.0))
           
            upload(midImage)
            //圖片控制器退出
            picker.dismissViewControllerAnimated(true, completion: {
                () -> Void in
            })
    }
   
    //圖片等比例壓縮
    func imageWithImageSimple(image:UIImage,scaledToSize newSize:CGSize)->UIImage
    {
        var width:CGFloat!
        var height:CGFloat!
        //等比例縮放
        if image.size.width/newSize.width >= image.size.height / newSize.height{
            width = newSize.width
            height = image.size.height / (image.size.width/newSize.width)
        }else{
            height = newSize.height
            width = image.size.width / (image.size.height/newSize.height)
        }
        let sizeImageSmall = CGSizeMake(width, height)
        //end
        print(sizeImageSmall)
       
        UIGraphicsBeginImageContext(sizeImageSmall);
        image.drawInRect(CGRectMake(0,0,sizeImageSmall.width,sizeImageSmall.height))
        let newImage:UIImage=UIGraphicsGetImageFromCurrentImageContext();
       
        UIGraphicsEndImageContext();
       
        return newImage;
    }
   
    func upload(img:UIImage)
       
    {
       
       
       
//        lb.frame=CGRectMake(0,0, self.view.bounds.size.width,20)
//        lb.textColor=UIColor.whiteColor()
//        lb.text="上傳中...."
//        lb.textAlignment=NSTextAlignment.Center
//        lb.backgroundColor=UIColor.blackColor()
//        lb.alpha=1
       
       
        //添加風火輪
        let av = UIActivityIndicatorView()
        av.frame=CGRectMake(200,200,20, 20)
        av.backgroundColor=UIColor.whiteColor()
        av.color=UIColor.redColor()
        av.startAnimating()
        self.view.addSubview(av)
       
        //self.view.addSubview(lb)
       
        let data=UIImagePNGRepresentation(img)//把圖片轉成data
        let uploadurl:String="http://xxxx/upload.php"//設置服務器接收地址
        let request=NSMutableURLRequest(URL:NSURL(string:uploadurl)!)
        request.HTTPMethod="POST"//設置請求方式
       
        let boundary:String="-------------------21212222222222222222222"
       
        let contentType:String="multipart/form-data;boundary="+boundary
       
        request.addValue(contentType, forHTTPHeaderField:"Content-Type")
       
        let body=NSMutableData()
       
        body.appendData(NSString(format:"\r\n--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
       
        body.appendData(NSString(format:"Content-Disposition:form-data;name=\"userfile\";filename=\"dd.jpg\"\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
       
        body.appendData(NSString(format:"Content-Type:application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
       
        body.appendData(data!)
       
        body.appendData(NSString(format:"\r\n--\(boundary)").dataUsingEncoding(NSUTF8StringEncoding)!)
       
        request.HTTPBody=body
       
        let que=NSOperationQueue()
       
        NSURLConnection.sendAsynchronousRequest(request, queue: que, completionHandler: {
           
            (response, data, error) ->Void in
            if (error != nil){
                print(error)
            }else{
                //Handle data in NSData type
                let tr:String=NSString(data:data!,encoding:NSUTF8StringEncoding)! as String
                print(tr)
                //在主線程中更新UI風火輪才停止
               
                dispatch_sync(dispatch_get_main_queue(), {
                    av.stopAnimating()
                    //self.lb.hidden=true
                })
            }
        })
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
    }

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


}


服務端的代碼:我寫的就簡單了:
<?php
move_uploaded_file($_FILES["userfile"]["tmp_name"],"1.jpg");
echo "1";
 
?>

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved