开发者

Compress Image File Size (iPhone)?

I have a simple iPhone app that allows the user to upload images to a server. The problem is, what if they upload a large image file. I want to limit it down to (a开发者_C百科 max of) 200 KB. I started something but it seems to crash in my while statement.

Here's the code:

NSString *jpgPath = [NSString stringWithFormat:@"Documents/%@",sqlImageUploadPathTwo];
NSString *jpgPathTwo = [NSString stringWithFormat:@"./../Documents/%@",sqlImageUploadPathTwo];
NSString *yourPath = [NSHomeDirectory() stringByAppendingPathComponent:jpgPath];

NSLog(@"yourPath: %@", yourPath);

NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
int *result = [attrs fileSize];
NSLog(@"Here's the original size: %d", result);

NSLog(@"jpgPath: %@ // jpgPathTwo: %@", jpgPath, jpgPathTwo);

while (result > 9715) {
    UIImage *tempImage = [UIImage imageNamed: jpgPath];
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(tempImage, 0.9)];
    [imageData writeToFile:jpgPathTwo atomically:YES];
    NSLog(@"just shrunk it once.");
}

NSLog(@"SIZE AFTER SHRINK: %@", result);

Thanks!

Coulton


Something like this: (also note that you declared result as int* (i.e. a pointer), instead of a number, and the condition should be >, not < (otherwise for large files it won't change them at all). And an extra counter condition is useful to avoid endless loop (basically do it 5 times and then stop doing it, regardless of the size).

NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
int result = [attrs fileSize];
int count = 0;
while (result > 9715 && count < 5) {
    UIImage *tempImage = [UIImage imageNamed: jpgPath];
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(tempImage, 0.9)];
    [imageData writeToFile:jpgPathTwo atomically:YES];
    NSDictionary *attrs = [man attributesOfItemAtPath: jpgPathTwo error: NULL];
    result = [attrs fileSize];
    count++;
    NSLog(@"just shrunk it once.");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜