IOS--圖片上傳

ASIFormDataRequest是ASIHttpRequest類庫的重要組成部分,本文就採用ASIFormDataRequest以POST方式實現圖片上傳。html

首先,要上傳圖片並非直接將圖片經過URL上傳的,而是要把圖片轉換爲二進制文件。json

IOS中有兩個方法能直接將圖片轉換爲二進制瀏覽器

UIImage *image = [UIImage imageNamed:@"xx.png"];
NSData *data = UIImagePNGRepresentation(image);
NSData *data2 = UIImageJPEGRepresentation(image,1);

就是採用如上兩種方法中的一個將一個圖片轉換爲二進制數據data,而後再將data數據上傳到網絡上。在這裏使用一個網絡請求三方庫ASIFormDataRequest。服務器

具體代碼以下:網絡

//用URL初始化請求
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
//設置代理
[request setDelegate:self];
//爲上傳對象添加數據
//上傳後保存的名字、保存類型、表單名
[request addData:dataWithFileName:@"xx.png" andContentType:@"image/png" forKey:@"file"];
//開始,異步
[request startAsynchronous];

如上就完成了圖片的上傳。框架

//剩下部分就是服務器端的事情
iphone

………………………………異步



方法二:post

1>IOS上傳圖片代碼ui

NSString *fileName = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
NSString *url = @"http://……/upload.aspx"; 
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
[request setPostValue:@"MyName" forkey:@"name"];
[request setFile:filename forkey:@"this_file"];
[request buildRequestHeaders];
NSLog(@"header:%@",request.requestHeaders);
[request startSynchronous];
NSLog(@"responseString = %@",request.requestHeaders);

2>服務器接收處理圖片代碼

public partial class upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpFileCollection MyFilecollection = Request.Files;
        MyFilecollection[0].SaveAs(Server.MapPath("~/ImageStore/" + MyFilecollection[0].FileName));
    }
}

服務器端代碼採用C++編寫。

方法三:

IOS經過http post上傳圖片、文件等

在http網絡請求中,post請求沒有長度的限制(由於post將數據放在body中),get是放在瀏覽器的地址欄中。

POST有兩種方式:

1>直接將數據放在body中,用contentType來區分類型是text仍是json或者別的類型,這種最簡單。

2>表單的形式,經過boundary來區分放置的是哪些數據,就像一個字典,用K、V放置對象。

經過咱們使用ASIHttp的第三方庫裏面的ASIFormDataRequest來模擬Form表單提交,提交格式Header會自動識別。

下面對比下ASIHttp與傳統POST的不一樣之處

NSMutableURLRequest傳統post用法

……這裏不介紹,自行百度。

下面介紹ASIHttp方法

NSURL *url = [NSURL URLWithString:@"請求地址"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"值1" forkey:@"參數1"];
[request setPostValue:@"值2" forkey:@"參數2"];
[request start];
NSError *error = [request error];
if(!error)
{
    NSString *response = [request responseString];
    NSLog("%@",response);
}



IOS攝像頭/本地相冊獲取圖片,壓縮圖片,上傳至服務器

iphone中,圖片一般存儲在4個地方(相冊、應用程序包、沙盒、Internet),經過這4個源,咱們就能夠存儲應用圖片。

1>相冊

用戶能夠經過UIImagePickerController類提供的交互對話框來從相冊中選擇圖片。可是,相冊中的圖片機器路徑沒法直接從應用程序訪問,只能經過終端用戶去選擇和使用相冊圖片。

2>應用程序包

應用程序包可能會將圖像與可執行程序、Info.plist文件和其餘資源一同存儲。咱們能夠經過本地文件路徑來讀取這些圖像並在應用程序中顯示它們。

3>沙盒

藉助沙盒,咱們能夠將圖片存儲到Documents、Library、tmp文件夾中。這些文件都可被應用程序讀取。

4>Internet

應用程序能夠經過圖片的URL來訪問Internet上的資源。

如上是一些小知識,來自《iphone開發祕籍(第二版)》,想了解更多,自主去查閱此書。

正題部分,從攝像頭/相冊獲取圖片、壓縮圖片、上傳圖片

1>從攝像頭/相冊中獲取圖片

由用戶瀏覽相冊並選擇圖片給程序使用,在這裏,咱們須要使用UIImagePickerController類來和用戶交互。使用UIImagePickerController類和用戶交互,必需要實現以下2個協議。從相冊獲取圖片,代碼以下:

  - (void)pickImageFromAlbum
  {
  imagePicker = [[UIImagePickerController alloc] init];
  imagePicker.delegate = self;
  imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  imagePicker.allowsEditing = YES;
  [self presentModalViewController:imagePicker animated:YES];
  }

如上代碼解釋

首先實例化UIImagePickerController對象,接着設置代理。設置圖片來源爲UIImagePickerControllerSourceTypePhotoLibrary ,代表當前圖片的來源爲相冊。

從攝像頭獲取圖片,代碼以下:

  - (void)pickImageFromCamera
  {
  imagePicker = [[UIImagePickerController alloc] init];
  imagePicker.delegate = self;
  imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  imagePicker.allowsEditing = YES;
  [self presentModalViewController:imagePicker animated:YES];
  }

以上代碼爲從攝像頭獲取圖片,和從相冊獲取圖片只是圖片的來源位置不同,攝像頭圖片的來源爲UIImagePickerControllerSourceTypeCamera 。

接着是用戶操做時間,用戶選擇好圖片後,就會 回調 選擇結束的方法,代碼以下:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  {
  UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
  if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
  {
  // UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
  }
  theImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(120.0, 120.0)];
  UIImage *midImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
  UIImage *bigImage = [UtilMethod imageWithImageSimple:image scaledToSize:CGSizeMake(440.0, 440.0)];
  [theImage retain];
  [self saveImage:theImage WithName:@"salesImageSmall.jpg"];
  [self saveImage:midImage WithName:@"salesImageMid.jpg"];
  [self saveImage:bigImage WithName:@"salesImageBig.jpg"];
  [self dismissModalViewControllerAnimated:YES];
  [self refreshData];
  [picker release];
  }

在回調方法中,須要對圖片進行大小處理,爲圖片的上傳作準備,如上代碼就是對圖片進行縮放,縮放代碼比較簡單,不作解釋。

接着對圖片進行壓縮處理,代碼以下:

  + (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
  {
  // Create a graphics image context
  UIGraphicsBeginImageContext(newSize);
  // Tell the old image to draw in this new context, with the desired
  // new size
  [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  // Get the new image from the context
  UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  // End the context
  UIGraphicsEndImageContext();
  // Return the new image.
  return newImage;
  }

接着是存儲圖片

經過以前的小知識瞭解,將應用程序所須要的一些圖片存入沙盒是個不錯的選擇,並且應用程序能夠直接經過路徑去訪問沙盒中的圖片,本例就將圖片存入沙盒中的Documents目錄下,代碼以下

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName

{

    NSData* imageData = UIImagePNGRepresentation(tempImage);

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString* documentsDirectory = [paths objectAtIndex:0];

    // Now we get the full path to the file

    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

    //and then we write it out

    [imageData writeToFile:fullPathToFile atomically:NO];

}

接下來是從Documents目錄下獲取圖片,要想從Documents下獲取圖片,首先要得到Documents目錄的路徑。代碼以下:

- (NSString *)documentFolderPath

{

    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

}

而後咱們能夠經過文件名,去訪問獲取資源了。

最後一步就是上傳圖片,這裏使用的是ASIFormHttpRequest開源框架,代碼以下:

  - (void)upLoadSalesBigImage:(NSString *)bigImage MidImage:(NSString *)midImage SmallImage:(NSString *)smallImage

{

    NSURL *url = [NSURL URLWithString:UPLOAD_SERVER_URL];

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    [request setPostValue:@"photo" forKey:@"type"];

    [request setFile:bigImage forKey:@"file_pic_big"];

    [request buildPostBody];

    [request setDelegate:self];

    [request setTimeOutSeconds:TIME_OUT_SECONDS];

    [request startAsynchronous];

}

以下就是實際的例子,在UIWebView中調用IOS相冊,並選擇圖片上傳到Linux Web服務器上。

//http://blog.sina.com.cn/s/blog_5fb39f910101ajua.html#

相關文章
相關標籤/搜索