5

ユーザーがiPhoneライブラリから画像を選択した後、ライブラリをUIImagePickerController使用してサーバーにアップロードしたいと思いますASIHTTPRequest

ファイルの URl を使用してファイルをアップロードできることはわかっていASIHTTPRequestますが、画像の URL を取得するにはどうすればよいですか?

UIImagePickerControllerReferenceURL次のような 画像を取得できることはわかっています。

"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"

これは私が使用する必要がある URL ですか?

4

6 に答える 6

5

UIImageJPEGRepresentation または UIImagePNGRepresentation を示唆する多くの回答があります。ただし、これらのソリューションは元のファイルを変換しますが、この質問は実際にはファイルをそのまま保存することに関するものです。

アセット ライブラリからファイルを直接アップロードすることはできないようです。ただし、実際の画像データを取得するために PHImageManager を使用してアクセスできます。方法は次のとおりです。

Swift 3 (Xcode 8、iOS 8.0 以降のみ)

1) 写真フレームワークをインポートする

import Photos

2) imagePickerController(_:didFinishPickingMediaWithInfo:) でアセット 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 を取得して正しい MIME タイプを特定することもできます (ファイル拡張子を介して特定することもできます)。

于 2017-01-11T10:59:39.780 に答える
4

2つの方法があります

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オブジェクトをシングルトンとして使用する場合は、オブジェクトのスコープを確認してください。

于 2012-08-27T08:44:35.730 に答える
3

写真を Document ディレクトリに保存し、その URL を使用してアップロードします。例:

NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImageJPEGRepresentation(img, 1.0) writeToFile:jpgPath atomically:YES];

この画像を次のようにアップロードし[request setFile:jpgPath forKey:@"image"]ます。

于 2012-08-27T09:29:02.093 に答える
1

画像の 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以降でのみ機能します。

于 2012-08-27T08:41:50.627 に答える
1

私が見つけた最も簡単な方法は

ステップ 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 : 必要に応じて画像を取得するには

このような参照を取得します

let 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)")
    }

}
于 2017-09-14T21:38:21.430 に答える
0

以下のコードを試してフォームを作成することで画像をアップロードできます

-(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];

  }
于 2012-08-27T09:14:33.807 に答える