Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASIHTTP: Upload UIImage?

Can someone please tell me how I can use an ASIHTTPRequest object in Objective-c to upload an UIImage object? Do I need to convert it to an NSData object?

(This is for an avatar upload url)

E.g. 

UIImage *toUpload = [UIImage imageNamed:@"test.jpg"]

URL: "http://www.example.com/api/users/avatar/upload?access_token=12345"
RequestType: PUT
like image 987
dpigera Avatar asked Jan 22 '11 22:01

dpigera


1 Answers

Heres an example using ASIFormRequest that will also attempt to compress the image to given maximum size

    //Compress the image
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:whereYourServerEndPointIs.com]];

[request addData:imageData withFileName:@"someFileName.jpeg" andContentType:@"image/jpeg" forKey:@"uploadedImage"];
like image 83
kgutteridge Avatar answered Nov 10 '22 16:11

kgutteridge