图片压缩动态获取图片高度

iOS开发 - 根据图片URL获取图片的尺寸(宽高)

https://www.jianshu.com/p/854dc9c810c9

第一种方法,基本上是无损压缩(肉眼基本看不出差别,不知到底损失了什么内容)

UIImageJPEGRepresentation(image, compression)
1
这个方法可以将iPhone6拍摄的照片压缩到几百Kb的极限值,到极限值之后不管compression这个参数多小,该函数返回的数据大小都不会再改变。也就是说这个方法的压缩是有最小值的。得到的是jpg格式。另外有一个方法UIImagePNGRepresentation(<#UIImage * _Nonnull image#>)这个方法得到的数据会比之前那个方法得到的数据占用空间更大。

第二种方法,基本上就是将image重新设定像素大小达到压缩的目的 
为了达到压缩的目的,这种方法是有损的,就是会降低图片质量。 
下面是压缩的方法

//压缩图片(将图片重画)
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //首先根据image的size的长宽比和newSize进行设置新图片的大小(为了达到等比例缩放不变形的目的)
    CGFloat wTmp;
    CGFloat hTmp;
    CGSize imgSize = image.size;
    if (imgSize.width > imgSize.height) {
        wTmp=newSize.width;
        hTmp = imgSize.height * wTmp / imgSize.width;
    } else {
        hTmp=newSize.height;
        wTmp = imgSize.width * hTmp / imgSize.height;
    }

    // Create a graphics image context
    UIGraphicsBeginImageContext(CGSizeMake(wTmp, hTmp));

    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,wTmp,hTmp)];

    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    // End the context
    UIGraphicsEndImageContext();

    // Return the new image.
    return newImage;
}

发布了49 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_29680975/article/details/87631266