ios - 在不影响 objective-c 质量的情况下缩小图像

标签 ios objective-c image shrink

如何在不影响质量的情况下以编程方式缩小图像。

捕获图像后,我想在不改变 objective-c 质量的情况下减小该图像的大小。

最佳答案

这是我用来压缩图片的代码

代码:

-(UIImage *)compressImage:(UIImage *)image{

    NSData *imgData = UIImageJPEGRepresentation(image, 1); //1 it represents the quality of the image.
    NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imgData length]);

    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = 600.0;
    float maxWidth = 800.0;
    float imgRatio = actualWidth/actualHeight;
    float maxRatio = maxWidth/maxHeight;
    float compressionQuality = 0.5;//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();

    NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imageData length]);

    return [UIImage imageWithData:imageData];
}

所以这是使用上面的代码

UIImage *org = [UIImage imageNamed:@"MacLehose Stage 7 Stunning Natural Sceneries.jpg"];

UIImage *imgCompressed = [self compressImage:org];

如果要压缩更多

NSData *dataImage = UIImageJPEGRepresentation(imgCompressed, 0.0);

NSLog(@"Size of Image(bytes):%ld",(unsigned long)[dataImage length]);

通过上述方式,我能够将图像从 2 MB 压缩到接近 50 KB。

关于ios - 在不影响 objective-c 质量的情况下缩小图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129215/

相关文章:

python - 如何使用 OpenCV 在 Python 中管理大图像?

ios - 制作自定义 View 并初始化它时的边界与框架

java - 我正在尝试使用 docx4j 将图像添加到新的 word 文档

IOS:停止在 UITableView 中错误地重用单元格

ios - UITableView - 更改与按下的按钮位于同一行的文本字段

ios - 是否可以在输出 ".a"库的项目中包含框架?

objective-c - 使用 block 会导致 EXC_BAD_ACCESS

javascript - 在 html 页面中显示来自 s3(亚马逊)的图像

ios - 尝试了解iOS开发中的AVAudioPlayer

ios - 点击表格 View 单元格时显示操作表