2016-06-18 49 views
1

如何从local url获得UIImage并将图像发布到服务器? 我url低于:如何从本地URL获取UIImage并将图像发布到服务器?

file:///Users/macmini/Library/Developer/CoreSimulator/Devices/89104EAC-5BE1-4BEC-BE8E-7B8FFBF9CBD2/data/Media/DCIM/100APPLE/IMG_0005.JPG 

以及如何减少这种尺寸图像

< UIImage: 0x7b8d6170>, {3000, 2002} 

预先感谢您..

+0

检查我的答案兄弟 –

回答

0

要从你可以做以下网址获得的图像。

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]; 
UIImage *image = [UIImage imageWithData:imageData]; 

要压缩它,你将不得不再次将其转换为NSData。

NSData *lowResImgData= UIImageJPEGRepresentation(highResImage,0.1 /*compressionQuality*/); 
UIImage *lowResImage = [UIImage imageWithData:lowResImgData]; 
0

使用此代码选择图像....

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) 
    { 
     UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; 
     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
     imagePicker.delegate = self; 
     imagePicker.allowsEditing = NO; 
     [self presentViewController:imagePicker animated:YES completion:nil]; 
    } 
    else 
    { 
     [self showMessage:@"This device doesn't support photo libraries." 
       withTitle:@"Error"]; 
    } 

使用下面的代码合并压缩

#pragma clang diagnostic ignored "-Wdeprecated-declarations"

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL]; 
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil]; 

    // to get the image image name use the following code 
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
    { 
     ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
     NSLog(@"[imageRep filename] : %@", [imageRep filename]); 
     [_imageNameArray addObject:[imageRep filename]]; 
    }; 

    [_uploadTbleView reloadData]; 
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; 
    [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil]; 


    UIImage* selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage]; 
    NSData *imgData = UIImageJPEGRepresentation(selectedImage, 1.0); 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     //  [self.baseArray addObject:[self encodeToBase64String: selectedImage]]; 
     [self.baseArray addObject:[self base64forData:imgData]]; 
     // NSLog(@"%@",[self encodeToBase64String: selectedImage]); 
    }); 
    [self.imageSizeArray addObject: [NSNumber numberWithInteger:[imgData length]]]; 
    NSLog(@"Size of Image(bytes):%ld",[imgData length]); 

} 

以下是代码将图像压缩到base64 bef矿石被上传

- (NSString*)base64forData:(NSData*) theData 
{ 
    const uint8_t* input = (const uint8_t*)[theData bytes]; 
    NSInteger length = [theData length]; 

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/="; 

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2)/3) * 4]; 
    uint8_t* output = (uint8_t*)data.mutableBytes; 

    NSInteger i; 
    for (i=0; i < length; i += 3) { 
     NSInteger value = 0; 
     NSInteger j; 
     for (j = i; j < (i + 3); j++) { 
      value <<= 8; 

      if (j < length) { 
       value |= (0xFF & input[j]); 
      } 
     } 

     NSInteger theIndex = (i/3) * 4; 
     output[theIndex + 0] =     table[(value >> 18) & 0x3F]; 
     output[theIndex + 1] =     table[(value >> 12) & 0x3F]; 
     output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; 
     output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; 
    } 

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
} 

注:

你又后端有这个的base64数据进行解码得到的图像内容。如果有任何问题,再打电话给我,我会帮助你

1

要想从local url图像:

NSURL *localurl = [NSURL URLWithString:path]; 
NSData *data = [NSData dataWithContentsOfURL:localurl]; 
UIImage *img = [[UIImage alloc] initWithData:data]; 

后的图像server

- (void)sendImageToServer { 
      UIImage *img= [UIImage imageNamed:@"image.png"]; 
      NSData *imageData = UIImagePNGRepresentation(img); 
      NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]]; 

      // Init the URLRequest 
      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
      [request setHTTPMethod:@"POST"]; 
      [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]]; 
      [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
      [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
      [request setHTTPBody:imageData]; 

      NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
      if (connection) { 
       // response data of the request 
      } 



} 
0

为了减少图像的大小使用以下方法

-(UIImage *)resizeImage:(UIImage *)image scaledToSize:(CGSize)targetSize 
{ 
    float actualHeight = image.size.height; 
    float actualWidth = image.size.width; 
    float maxHeight = targetSize.height; 
    float maxWidth = targetSize.width; 
    float imgRatio = actualWidth/actualHeight; 
    float maxRatio = maxWidth/maxHeight; 
    float compressionQuality = 0.50;//50 percent compression 

    if (actualHeight > maxHeight || actualWidth > maxWidth) 
    { 
     if(imgRatio < maxRatio) 
     { 
      //adjust width according to maxHeight 
      imgRatio = maxHeight/actualHeight; 
      actualWidth = imgRatio * actualWidth; 
      actualHeight = maxHeight; 
     } 
    else if(imgRatio > maxRatio) 
{ 
    //adjust height according to maxWidth 
    imgRatio = maxWidth/actualWidth; 
    actualHeight = imgRatio * actualHeight; 
    actualWidth = maxWidth; 
} 
else 
{ 
    actualHeight = maxHeight; 
    actualWidth = maxWidth; 
} 
} 

CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight); 
UIGraphicsBeginImageContext(rect.size); 
[image drawInRect:rect]; 
UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality); 
UIGraphicsEndImageContext(); 
return [UIImage imageWithData:imageData]; 

}

请看看下面的URL来在你的服务器上载入图像。

ios Upload Image and Text using HTTP POST

0

要压缩的UIImage,这取决于你demand.According到的压缩或按照sizeThe压缩质量。

第一种方式(质量),使用API​​如下:

UIImageJPEGRepresentation(UIImage * __nonnull image, CGFloat compressionQuality) 

第二种方式,使用的代码如下:

+ (UIImage*)imageWithImage:(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; 
} 

要上传您的本地图片文件到服务器,如果你使用AFNetWorking 3.x,这样的代码可能适用于你:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:host]]; 
[manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { 
    //local file url,for you is /Users/macmini/Library/Developer/CoreSimulator/Devices/89104EAC-5BE1-4BEC-BE8E-7B8FFBF9CBD2/data/Media/DCIM/100APPLE/IMG_0005.JPG 
    NSURL *url = [NSURL fileURLWithPath:fileUrl]; 
    [formData appendPartWithFileURL:url name:name fileName:fileName mimeType:mimeType error:nil]; 
} progress:^(NSProgress * _Nonnull uploadProgress) { 

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 
    if (successBlock) { 
     if (responseObject) { 
      successBlock(responseObject); 
     } 
    } 
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 
    if (failureBlock) { 
     HttpFailResponse *failResponse = [self _kep_configureFailResponseWithError:error]; 
     failureBlock(failResponse); 
    } 
}]; 
相关问题