Iphone 如何上载从UIImagePickerController获取的图像
用户使用Iphone 如何上载从UIImagePickerController获取的图像,iphone,objective-c,ios,uiimagepickercontroller,asihttprequest,Iphone,Objective C,Ios,Uiimagepickercontroller,Asihttprequest,用户使用UIImagePickerController从iPhone库中选择图像后,我想使用ASIHTTPRequest库将其上载到我的服务器 我知道使用ASIHTTPRequest我可以上传带有文件URl的文件,但是如何获取图像URl 我知道我可以获取图像UIImagePickerController参考URL,如下所示: "assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"
UIImagePickerController
从iPhone库中选择图像后,我想使用ASIHTTPRequest
库将其上载到我的服务器
我知道使用ASIHTTPRequest
我可以上传带有文件URl的文件,但是如何获取图像URl
我知道我可以获取图像
UIImagePickerController参考URL
,如下所示:
"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"
这是我需要使用的URL吗?来获取图像UIImagePickerControllerReferenceUR。下面给出了这个示例代码
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
NSString *fileName = [representation filename];
NSLog(@"fileName : %@",fileName);
CGImageRef ref = [representation fullResolutionImage];
ALAssetOrientation orientation = [[myasset valueForProperty:@"ALAssetPropertyOrientation"] intValue];
UIImage *image = [UIImage imageWithCGImage:ref scale:1.0 orientation:(UIImageOrientation)orientation];
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:imageURL
resultBlock:resultblock
failureBlock:nil];
}
注意:它仅适用于iOS 5及更高版本。有两种方法
1:
您可以使用imagePickerController委托上载图像
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
//Upload your image
}
2:
您可以保存拾取的图像url,稍后使用此
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString *imageUrl = [NSString stringWithFormat:@"%@",[info valueForKey:UIImagePickerControllerReferenceURL]];
//Save the imageUrl
}
-(void)UploadTheImage:(NSString *)imageUrl{
NSURL *url = [[NSURL alloc] initWithString:imageUrl];
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
UIImage *myImage = nil;
if (ref) {
myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
//upload the image
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:url resultBlock:result block failureBlock:failureblock];
}
注意:在使用ARC时,请确保
AlassetLibrary
对象的范围。最好将AlassetLibrary
对象作为一个单独的对象使用。您可以通过创建表单上传图像,请在下面尝试代码
-(void)UploadImage{
NSString *urlString = @"yourUrl";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
// file
NSData *imageData = UIImageJPEGRepresentation([self scaleAndRotateImage:[selectedImageObj]],90);
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[[NSString stringWithString:@"Content-Disposition: attachment; name=\"user_photo\"; filename=\"photoes.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@.jpg\"\r\n",@"ImageNmae"] 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 stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
将照片保存在文档目录中,并使用该url上载
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImageJPEGRepresentation(img, 1.0) writeToFile:jpgPath atomically:YES];
将此图像上载为
[请求集文件:jpgPath forKey:@“image”]
有很多答案建议使用UIImageJPEG表示法或UIImagePNGRE表示法。但是这些解决方案将转换原始文件,而这个问题实际上是关于按原样保存文件
看起来直接从资产库上传文件是不可能的。但是可以使用PHImageManager访问它以获得实际的图像数据。以下是方法:
Swift 3(Xcode 8,仅适用于iOS 8.0及更高版本)
1) 导入照片框架
import Photos
2) 在imagePickerController中(uxFinishPickingMediaWithInfo:)获取资产URL
3) 使用fetchAssets获取资产(withALAssetURLs:options:)
4) 使用requestImageData获取实际图像数据(for:options:resultHandler:)。在该方法的结果处理程序中,您将获得数据以及文件的URL(该URL可以在模拟器上访问,但不幸的是在设备上无法访问-在我的测试中,startAccessingSecurityScopedResource()始终返回false)。但是,此URL对于查找文件名仍然很有用
示例代码:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true, completion: nil)
if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL,
let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject,
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
let targetURL = Foundation.URL(string: "file://\(documentsPath)") {
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { (data, UTI, _, info) in
if let imageURL = info?["PHImageFileURLKey"] as? URL,
imageData = data {
do {
try data.write(to: targetURL.appendingPathComponent(imageURL.lastPathComponent), options: .atomic)
self.proceedWithUploadFromPath(targetPath: targetURL.appendingPathComponent(imageURL.lastPathComponent))
} catch { print(error) }
}
}
})
}
}
这将为您提供包含正确名称的文件,您甚至可以让其UTI确定正确的mimetype(除了通过文件扩展名确定它),同时准备上传多部分正文。我找到的最简单的方法是 步骤1:获取文档目录的路径
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
return documentsFolderPath.appendingPathComponent(filename)
}
步骤2:使用tempFileName保存在路径
func saveImage(image: UIImage, path: String ) {
let pngImageData = UIImagePNGRepresentation(image)
do {
try pngImageData?.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
print(error)
}
}
步骤3:在imagePickerController功能中使用
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {// image asset
self.saveImage(image: image, path: fileInDocumentsDirectory(filename: "temp_dummy_image.png"))
}
步骤4:在需要时获取图像
像这样获取引用
让localfilepath=self.fileInDocumentsDirectory(文件名:“temp\u dummy\u image.png”)
步骤5:使用映像后,要清除临时映像
func removeTempDummyImagefileInDocumentsDirectory(filename: String) {
let fileManager = FileManager.default
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItem(atPath: filePathName)
}
}
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
将图像转换为NSData,然后上传它,但我知道可以直接从文件系统上传,我更喜欢这样做参见NSURL*url=[NSURL URLWithString:imagePath];NSData*data=[NSData dataWithContentsOfURL:url];“这是我需要使用的URL吗?”当您使用该URL时,它是否起作用?我相信,这种库方式将导致应用程序向用户请求位置权限,这并不理想-第一种方式可以避免这种情况。我们是否有理由将URL存储为字符串,以便稍后将其膨胀回来?存储url是否更昂贵?ALAssetRepresentation不受欢迎DuiImagePickerControllerReferenceURL不受欢迎:(