IT虾米网

iOS对图像进行压缩代码

wyy 2018年06月24日 手机开发 833 0
- (UIImage*)scaleFromImage:(UIImage*)image scaledToSize:(CGSize)newSize 
{ 
 CGSize imageSize = image.size; 
 CGFloat width = imageSize.width; 
 CGFloat height = imageSize.height; 
 
 if (width <= newSize.width && height <= newSize.height){ 
  return image; 
 } 
 
 if (width == 0 || height == 0){ 
  return image; 
 } 
 
 CGFloat widthFactor = newSize.width / width; 
 CGFloat heightFactor = newSize.height / height; 
 CGFloat scaleFactor = (widthFactor<heightFactor?widthFactor:heightFactor); 
 
 CGFloat scaledWidth = width * scaleFactor; 
 CGFloat scaledHeight = height * scaleFactor; 
 CGSize targetSize = CGSizeMake(scaledWidth,scaledHeight); 
 
    UIGraphicsBeginImageContext(targetSize); 
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 

评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!