• 图片压缩,别问我是谁,请叫我雷锋


    First. You should建立一个UIImage的category,叫Helper

    Second.   so,UIImage+Helper.h中:

    //图片压缩

    - (UIImage *)compressedImage;

    //将Image转换成NSData

    - (NSData *)imageData;

    UIImage+Helper.m中:

    #import "UIImage+Helper.h"

    #define MAX_IMAGE_WIDTH_PIX 800.0    //max pix 200.0px

    #define MAX_IMAGE_HEIGHT_PIX 800.0

    #define MAX_IMAGEDATA_LEN 50000.0

    @implementation UIImage (Helper)

    - (UIImage *)compressedImage{

        CGSize imageSize = self.size;

        CGFloat width = imageSize.width;

        CGFloat height = imageSize.height;

        

        if (width <= MAX_IMAGE_WIDTH_PIX && height <= MAX_IMAGE_HEIGHT_PIX) {

            //no need to compress.

            return self;

        }

        if (width == 0 || height == 0) {

            //void zero exception

            return self;

        }

        UIImage * newImage = nil;

        CGFloat widthFactor = MAX_IMAGE_WIDTH_PIX/width;

        CGFloat heightFactor = MAX_IMAGE_HEIGHT_PIX/height;

        CGFloat scaleFactor = 0.0;

        if (widthFactor > heightFactor) {

            scaleFactor = heightFactor; //scale to fit height

        }

        else{

            scaleFactor = widthFactor; //scale to fit width

        }

        CGFloat scaledWidth = width * scaleFactor;

        CGFloat scaledHeight = height * scaleFactor;

        CGSize targetSize = CGSizeMake(scaledWidth, scaledHeight);

        

        UIGraphicsBeginImageContext(targetSize);//this wil crop

        

        CGRect thumbnailRect = CGRectZero;

        thumbnailRect.size.width = scaledWidth;

        thumbnailRect.size.height = scaledHeight;

        

        [self drawInRect:thumbnailRect];

        

        newImage = UIGraphicsGetImageFromCurrentImageContext();

        

        //pop the context to get back to the default

        UIGraphicsEndImageContext();

        return newImage;

    }

    - (NSData *)imageData{

        return UIImageJPEGRepresentation(self, 1);

    }

    对了,图片的压缩一般多用于上传图片,所以要将图片转换成NSData 

  • 相关阅读:
    用友 t6 凭证http API
    vue 解决 跳转外部地址携带根路径问题
    JavaScript之assign()——对象浅拷贝 (ES6)
    JavaScript之splice 添加或删除元素
    JavaScript之“==”和“===”
    C#——获取阶乘(递归、循环)
    C#——简单的表示两个数中的(三目运算)
    JavaScript 字符串之截取字符串 ——(substring、substr、slice)
    JavaScrpit之Json实现深拷贝
    Vue之this.$forceUpdate——强制更新数据
  • 原文地址:https://www.cnblogs.com/zhouyantongiOSDev/p/4371437.html
Copyright © 2020-2023  润新知