【问题标题】:Compress Image File Size (iPhone)?压缩图像文件大小 (iPhone)?
【发布时间】:2011-04-07 03:22:37
【问题描述】:

我有一个简单的 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);

谢谢!
库尔顿

【问题讨论】:

  • 看起来你没有在 while 语句中改变结果,所以你有一个无限循环。
  • 我压缩它直到它低于一个设定的限制(在这个例子中,9715字节)。压缩后是否需要拨打result?谢谢!
  • 不,我的意思是变量“result”在while循环中没有改变,所以如果它最初是> = 9715,循环永远不会结束,你会遇到堆栈溢出崩溃。
  • 所以如果我只是调用它来更新保存后循环中的result,它会起作用吗?
  • 还有几个问题 - 查看答案。

标签: objective-c xcode ios4 uiimage


【解决方案1】:

类似这样的: (另请注意,您将结果声明为 int*(即指针),而不是数字,并且条件应该是 >,而不是

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.");
}

【讨论】:

  • 谢谢!差不多好了。由于这条线,它每次都会崩溃:UIImage *tempImage = [UIImage imageNamed: jpgPath];。无论如何,我们可以在while 声明的末尾发布它吗?
  • 你不需要释放它,它会自动完成。控制台中关于崩溃的内容是什么?它在哪个迭代中崩溃?请注意,您应该真正从 jpgPathTwo 加载 tempImage,而不是 jpgPath,否则它每次都会从头开始调整大小。
  • 我定义了它,将它设置为 nil,然后使用 imagedNamed 并且它起作用了。感谢您的帮助。