我有一个简单的iPhone应用程序,允许用户将图像上传到服务器。问题是,如果他们上传大图像文件会怎么样。我想将其限制为(最大)200 KB。我开始了一些事情,但似乎在while
声明中崩溃了。
以下是代码:
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);
谢谢!
库尔顿
答案 0 :(得分:4)
这样的事情: (另请注意,您将结果声明为int *(即指针),而不是数字,条件应为>,而不是<(对于大文件,它根本不会更改它们。)还有一个额外的计数器条件对于避免无限循环很有用(基本上做5次然后停止这样做,无论大小如何)。
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.");
}