0

how to get UIImage from local url and post the image to server ? My url is below:

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

and how to reduce size of this image

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

Thank you in advance..

Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
ragu
  • 133
  • 2
  • 10

5 Answers5

2

To get the image from local url :

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

Post the image to 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
           }



 }
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
1

Use this code for picking image....

 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"];
    }

Use the following code to incorporate compression

#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]);

}

Following is the code that compresses the image to base64 before being uploaded

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

NOTE:

your backend in turn has to decode this base64 data to get the image content. If there is any issues, get back again to me and i will help you out

  • Great answer in detail! Just a quick addition: data isn't *compressed* into base64. It's *encoded*, and in this context it's actually expanded, as base64 encoding is much longer than the actual data. – Can Poyrazoğlu Nov 12 '18 at 09:32
0

To get an image from URL you can do following.

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

To compress it you will have to convert it to NSData again.

NSData *lowResImgData= UIImageJPEGRepresentation(highResImage,0.1 /*compressionQuality*/);
UIImage *lowResImage = [UIImage imageWithData:lowResImgData];
slonkar
  • 4,055
  • 8
  • 39
  • 63
0

To reduce the size of the image use this following method

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

}

Please take a look at following url to uppload image in your server.

ios Upload Image and Text using HTTP POST

Community
  • 1
  • 1
Gour
  • 50
  • 8
0

To compress UIImage,it depends on you demand.According to the quality of compressed or According to the sizeThe compression.

The first way(quality),use API as follow:

UIImageJPEGRepresentation(UIImage * __nonnull image, CGFloat compressionQuality)

The second way,use code as follow:

+ (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;
}

To upload you local image file to server,if you use AFNetWorking 3.x,such code may avaiable to you:

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);
    }
}];
ThomasLee
  • 17
  • 5