您的位置:首页 > 移动开发 > IOS开发

IOS上传照片(自己的代码整理了一下)

2012-08-30 19:11 218 查看
IOS上传照片源代码

UploadPhotoViewController.h 头文件

#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
@interface UploadPhotoViewController :UIViewController<MBProgressHUDDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
MBProgressHUD *HUD;
}
-(void) snapImage;//拍照
-(void) pickImage;//从相册里找
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size;//把图缩放到合适的尽寸
@end


UploadPhotoViewController.m 源文件

#import "UploadPhotoViewController.h"
#import"ASIFormDataRequest.h"//ASIRequest用来上传图片
#import"HJManagedImageV.h"  //HJManagedImageV是图片缓存类,可以用其它异步加载图片类取代
#import "JSON.h"
#define UPLOAD_URL @"http://localhost/upload.php"//上传地址
@implementation UploadPhotoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[superdidReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title =@"上代图片例子";
}

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

HJManagedImageV* mi = [[[HJManagedImageValloc] initWithFrame:CGRectMake(20,20,280,280)]autorelease];
mi.url = [NSURL URLWithString:@"图片地址"]];
[mi showLoadingWheel];
mi.tag = 777 ;
[self.scrollView addSubview:mi];
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[mi setCallbackOnImageTap:self method:@selector(uploadPortrait:)];//点击图片,执行上传图片操作
[appDelegate.objMan manage:mi];//加载图片
}

- (void)viewDidUnload
{
[superviewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
[super dealloc];
}

//上传图片操作开始,选择图片的来源
-(void)uploadPortrait:(id)sender{
UIActionSheet *menu = [[UIActionSheetalloc]
initWithTitle: @"更改图片"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:nil
otherButtonTitles:@"拍照",@"从相册上传",nil];
menu.actionSheetStyle =UIActionSheetStyleBlackTranslucent;
[menu showInView:self.navigationController.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0){
[self snapImage];
}else if(buttonIndex ==1){
[self pickImage];
}
[actionSheet release];
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(0,0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
//返回新的改变大小后的图片
return scaledImage;
}
-(void)uploadPortraitTask:(NSDictionary *)info{
// Do something usefull in here instead of sleeping ...
NSURL *URL = [NSURLURLWithString:UPLOAD_URL];
ASIFormDataRequest *Request = [ASIFormDataRequestrequestWithURL:URL];
[Request setRequestMethod:@"POST"];
[Request addRequestHeader:@"Content-Type"value:@"application/json"];
[Request setTimeOutSeconds:60];

//[Request setPostValue:auth forKey:@"auth"];
UIImage *img = [selfscaleToSize:[infoobjectForKey:@"UIImagePickerControllerOriginalImage"]size:CGSizeMake(300,300)];
[Request setData:UIImagePNGRepresentation(img)forKey:@"file"];

[Request setDelegate:self];
[Request setCompletionBlock:^{
NSString *responseString = [Request responseString];
//NSLog(@"Response: %@", responseString);
NSDictionary *info = [responseString JSONValue];
NSNumber *status = [info objectForKey:@"status"];
if([status intValue]==1){
HJManagedImageV* mi = (HJManagedImageV *)[self.viewviewWithTag:777];
//set the URL that we want the managed image view to load
[mi clear];
mi.url = [NSURLURLWithString:[info objectForKey:@"filePath"]];
[mi showLoadingWheel];
mi.tag = 777 ;
IBMEventAppDelegate *appDelegate = (IBMEventAppDelegate *)[[UIApplicationsharedApplication] delegate];
//[mi setCallbackOnImageTap:self method:@selector(uploadPortrait:)];
[appDelegate.objMan manage:mi];
[appDelegate loadLoginInfoData];
UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:@"图片上传成功!" delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[av show];

}else if([statusintValue]==-1){
UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[info objectForKey:@"msg"]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[av show];
}else{
UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[info objectForKey:@"msg"]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[av show];
}
[MBProgressHUDhideHUDForView:self.navigationController.viewanimated:YES];
}];
[Request setFailedBlock:^{
NSError *error = [Request error];
NSLog(@"Error: %@,%@", error.localizedDescription,Request.url);
}];
[Request startSynchronous];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
if (!error){
UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:@"Image written to photo album"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[av show];
}else{
UIAlertView *av=[[[UIAlertViewalloc] initWithTitle:nilmessage:[NSStringstringWithFormat:@"Error writing to photo album: %@",[errorlocalizedDescription]] delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[av show];
}

}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
HUD = [MBProgressHUDshowHUDAddedTo:self.navigationController.viewanimated:YES];
HUD.dimBackground =YES;
HUD.delegate =self;
HUD.labelText =@"请稍等";
HUD.square =YES;
[HUDshowWhileExecuting:@selector(uploadPortraitTask:)onTarget:selfwithObject:info animated:YES];
//SETIMAGE([info objectForKey:@"UIImagePickerControllerOriginalImage"]);
[selfdismissModalViewControllerAnimated:YES];
[picker release];
}

// Provide 2.x compliance
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
NSDictionary *dict = [NSDictionarydictionaryWithObject:imageforKey:@"UIImagePickerControllerOriginalImage"];
[selfimagePickerController:picker didFinishPickingMediaWithInfo:dict];
}

// Optional but "expected" dismiss
/*
- (void) imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
[picker release];
}
*/

- (void) pickImage
{
UIImagePickerController *ipc = [[UIImagePickerControlleralloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
ipc.delegate =self;
ipc.allowsEditing =NO;
[selfpresentModalViewController:ipc animated:YES];
}

- (void) snapImage
{
UIImagePickerController *ipc = [[UIImagePickerControlleralloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
ipc.delegate =self;
ipc.allowsEditing =NO;
[selfpresentModalViewController:ipc animated:YES];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: