相册
iphone的相册包含摄像头胶卷+用户计算机同步的部分照片。用户可以通过UIImagePickerController类提供的交互对话框来从相册中选择图像。但是,注意:相册中的图片机器路径无法直接从应用程序访问,只能通过终端用户去选择和使用相册图片
应用程序包
应用程序包可能会将图像与可执行程序、Info.plist文件和其他资源一同存储。我们可以通过本地文件路径来读取这些基于包的图像并在应用程序中显示它们。
沙盒
借助沙盒,我们可以把图片存储到Documents、Library、tmp文件夹中。这些文件均可有应用程序读取,且可以通过文件路径创建图像。尽管沙盒外的部分从技术上说是可行的,但是apple表明这些部分不在appstore应用程序允许访问的范围之内。
Internet
应用程序可以通过图片的URL来访问Internet上的资源。
以上为一些小知识,来自《iphone开发秘籍(第二版)》,可以自己去参考此书。
下面开始切入正题,从摄像头/相册获取图片,压缩图片,上传图片。
从摄像头/相册获取图片
刚刚在上面的知识中提到从摄像头/相册获取图片是面向终端用户的,由用户去浏览并选择图片为程序使用。在这里,我们需要过UIImagePickerController类来和用户交互。
使用UIImagePickerController和用户交互,我们需要实现2个协议。
代码如下
#pragma mark 从用户相册获取活动图片
- (void)pickImageFromAlbum
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagePicker.allowsEditing = YES;
[self presentModalViewController:imagePicker animated:YES];
}
我们来看看上面的从相册获取图片,我们首先要实例化UIImagePickerController对象,然后设置imagePicker对象为当前对象,设置imagePicker的图片来源为UIImagePickerControllerSourceTypePhotoLibrary,表明当前图片的来源为相册,除此之外还可以设置用户对图片是否可编辑。
代码如下
#pragma mark 从摄像头获取活动图片
- (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目录下。
代码如下
#pragma mark 保存图片到document
- (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目录的路径。
代码如下
#pragma mark 从文档目录下获取Documents路径
- (NSString *)documentFolderPath
{
return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}
然后,我们便可以通过文件名,去访问获取资源了。
上传图片
项目中我们使用了ASIFormHttpRequest的开源框架,http请求的部分代码如下,http返回以及相关回调方法略去。
代码如下
- (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服务器。
(2012-08-09 17:03:29)
//
// ViewController.h
// Xcode_FileUpload
//
// Created by KirSsu Ryu on 12-8-7.
// Copyright (c) 2012年 __JModule__. All rights reserved.
//
#import
//UIWebViewDelegate 代理类:跟javascript相互传值。
//UINavigationControllerDelegate,UIImagePickerControllerDelegate 代理类:打开相册等一系列操作。
@interface ViewController : UIViewController<</SPAN>UIWebViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
UIWebView *myWebView;
UIImagePickerController *picker_library_;
}
//我的WebView控件
@property (nonatomic, retain) IBOutlet UIWebView *myWebView;
//相册类的变量
@property (nonatomic, retain) IBOutlet UIImagePickerController *picker_library_;
@end
//
// ViewController.h
// Xcode_FileUpload
//
// Created by KirSsu Ryu on 12-8-7.
// Copyright (c) 2012年 __JModule__. All rights reserved.
//
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
@synthesize myWebView;
@synthesize picker_library_;
- (void)viewDidLoad
{
[super viewDidLoad];
//代理UIWebViewDelegate
myWebView.delegate = self;
//设置要载入的链接
NSURL *url = [NSURL URLWithString:@"http://*****/test/index.php"];
//创建一个请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//把请求发送到webView里,实现显示内容
[myWebView loadRequest:request];
}
- (void)viewDidUnload
{
[self setMyWebView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
//获得从网站得到的值
#pragma mark --
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//获得请求的URL,第一次是路径,当在web上点击按钮后获得的是web穿过来的路径。
NSString *requestString = [[request URL] absoluteString];
//根据":"拆分字符串,返回数组。
NSArray *components = [requestString componentsSeparatedByString:@":"];
//如果数组内的元素大于1并且第一个元素的值相等
if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"gallery"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"open"])
{
[self openGallery];
}
return NO;
}
return YES;
}
//打开相册
-(void)openGallery{
//初始化类
picker_library_ = [[UIImagePickerController alloc] init];
//指定几总图片来源
//UIImagePickerControllerSourceTypePhotoLibrary:表示显示所有的照片。
//UIImagePickerControllerSourceTypeCamera:表示从摄像头选取照片。
//UIImagePickerControllerSourceTypeSavedPhotosAlbum:表示仅仅从相册中选取照片。
picker_library_.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//表示用户可编辑图片。
picker_library_.allowsEditing = YES;
//代理
picker_library_.delegate = self;
[self presentModalViewController: picker_library_
animated: YES];
}
//3.x 用户选中图片后的回调
- (void)imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary *)info
{
NSLog(@"3.x");
//获得编辑过的图片
UIImage* image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
[self dismissModalViewControllerAnimated:YES];
[self imageUpload:image];
}
//2.x 用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
NSLog(@"2.x");
NSMutableDictionary * dict= [NSMutableDictionary dictionaryWithDictionary:editingInfo];
[dict setObject:image forKey:@"UIImagePickerControllerEditedImage"];
//直接调用3.x的处理函数
[self imagePickerController:picker didFinishPickingMediaWithInfo:dict];
}
// 用户选择取消
- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
//上传图片方法
- (void) imageUpload:(UIImage *) image{
//把图片转换成imageDate格式
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
//传送路径
NSString *urlString = @"http://*****/test/upload.php";
//建立请求对象
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
//设置请求路径
[request setURL:[NSURL URLWithString:urlString]];
//请求方式
[request setHTTPMethod:@"POST"];
//一连串上传头标签
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="vim_go.jpg"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//上传文件开始
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//获得返回值
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
}
@end