压缩图片到指定大小

/**

  • 压缩图片到指定文件大小
  • @param image 目标图片
  • @param size 目标大小(最大值),例如最大2M,就传2.0
  • @return 返回的图片文件
    */
  • (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size {
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = size-0.01;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
    maxQuality = maxQuality - 0.01f;
    data = UIImageJPEGRepresentation(image, maxQuality);
    dataKBytes = data.length / 1000.0;
    if (lastData == dataKBytes) {
    break;
    }else{
    lastData = dataKBytes;
    }
    }
    return data;
    }

你可能感兴趣的:(压缩图片到指定大小)