美文网首页
iOS开发之图片等比压缩

iOS开发之图片等比压缩

作者: 右庶长 | 来源:发表于2016-11-26 17:29 被阅读43次

需求

  • 在上传头像的时候,往往规定了图片的尺寸和容量大小,这时候对相册内的图片要进行等比压缩

解决

  • 给UIImage添加分类,实现一个等比压缩的方法,具体如下
    • 传入的指定的压缩宽度
    • 计算压缩后的高度
    • 开启图形上下文
    • 通过图形上下文获取压缩后的图片
- (UIImage *)compressWithWidth:(CGFloat)scaleWidth{

    //压缩后的高度
    CGFloat scaleHeight = scaleWidth/self.size.width * self.size.height;
    CGSize size = CGSizeMake(scaleWidth, scaleHeight);
    
    //开启图形上下文
    UIGraphicsBeginImageContext(size);
    
    //图片绘制到指定区域内
    [self drawInRect:CGRectMake(0, 0, scaleWidth, scaleHeight)];
    
    //通过图形上下文获取压缩后的图片
    UIImage *scaleImage = UIGraphicsGetImageFromCurrentImageContext();
    
    return scaleImage;
}

demo地址

demo地址

相关文章

网友评论

      本文标题:iOS开发之图片等比压缩

      本文链接:https://www.haomeiwen.com/subject/otrgpttx.html