用户选择后,从iPhone库图像UIImagePickerController
,我希望把它上传到使用我的服务器ASIHTTPRequest
库。
我知道,与ASIHTTPRequest
我可以上传与文件的URL文件,但如何取得图片网址?
我知道我可以得到图像UIImagePickerControllerReferenceURL
,看起来像这样:
"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"
这是我需要使用的网址是什么?
Answer 1:
有两种方法
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];
}
注:请确保的范围ALAssetsLibrary
对象,而使用ARC.Better使用ALAssetsLibrary
对象作为一个单身。
Answer 2:
保存在文件目录中的照片,并使用该网址upload.For例子
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImageJPEGRepresentation(img, 1.0) writeToFile:jpgPath atomically:YES];
载此图像作为[request setFile:jpgPath forKey:@"image"]
;
Answer 3:
有很多答案的暗示UIImageJPEGRepresentation或UIImagePNGRepresentation。 不过,虽然这个问题实际上是关于将文件保存为在这些解决方案将转换成原始文件。
它看起来像直接上传从资产库是不可能的文件。 但是,它可以使用PHImageManager获得实际的图像数据进行访问。 这是如何做:
迅速3(的Xcode 8中,仅针对iOS 8.0和更高)
1)导入照片框架
import Photos
2)在imagePickerController(_:didFinishPickingMediaWithInfo :)获得资产网址
3)获取使用fetchAssets(withALAssetURLs资产:选择:)
4)requestImageData(为获取实际的图像数据:选择:resultHandler :)。 在这种方法中,你将有数据以及URL到文件的结果处理(网址可以在模拟器能够访问,但不幸的是,不是设备上访问 - 在我的测试startAccessingSecurityScopedResource()总是返回false)。 然而这个网址仍然是有用的找出文件名。
示例代码:
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,以确定正确的MIME类型(除了通过文件扩展名确定的话),同时准备多身体上载。
Answer 4:
为了获得图像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及更高版本。
Answer 5:
我发现最简单的方法是
第1步:获取路径DocumentsDirectory
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_dummy_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)")
}
}
Answer 6:
你可以通过创建形式上传图像尝试下面的代码
-(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];
}
文章来源: How to upload image that was taken from UIImagePickerController