如何从本地URL获取UIImage并将图像发布到服务器?

时间:2016-06-18 05:32:01

标签: ios objective-c uiimage

如何从local url获取UIImage并将图片发布到服务器? 我的url位于以下位置:

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

以及如何减少此图片的尺寸

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

提前谢谢..

5 个答案:

答案 0 :(得分:2)

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
           }



 }

答案 1 :(得分:1)

使用此代码挑选图片....

 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的代码

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

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    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数据以获取图像内容。如果有任何问题,请再次回复我,我会帮助您

答案 2 :(得分: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];

答案 3 :(得分: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];

}

请查看以下网址以在您的服务器中重置图片。

ios Upload Image and Text using HTTP POST

答案 4 :(得分:0)

要压缩UIImage,它取决于你的需求。根据压缩的质量或根据大小的压缩。

第一种方式(质量),使用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);
    }
}];