iOS 压缩图片,判断图片格式

来源:互联网 发布:网络侦探dlc 编辑:程序博客网 时间:2024/05/29 14:43

最近在做上传图片处理,遇到了不少麻烦,比如用相机拍出来的图片太大,取得的图片方向有问题等。

图片方向的问题,请看     

点击打开链接



对图片进行压缩的话,网上看了些资料也就是:

1.改变图片的大小

2.改变图片的质量


1.改变图片大小的方法

  可以搞一个  UIImage+XX  的分类

** //对图片尺寸进行压缩-- */+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{    // Create a graphics image context    UIGraphicsBeginImageContext(newSize);        // Tell the old image to draw in this new context, with the desired    // new size    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];        // Get the new image from the context    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();        // End the context    UIGraphicsEndImageContext();        // Return the new image.    return newImage;}


进行压缩

// 压缩        CGFloat proportion = (CGFloat)(editedImage.size.width/editedImage.size.height);        UIImage *image =  [UIImage imageWithImage:editedImage scaledToSize:CGSizeMake(500, (CGFloat)500/proportion)];

proportion
     比例

editedImage
原始图片

然调用方法

/** //对图片尺寸进行压缩-- */+(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;

获得一张新图片


1.改变图片质量的方法 

/** //压缩图片质量 */+(UIImage *)reduceImage:(UIImage *)image percent:(float)percent{    NSData *imageData = UIImageJPEGRepresentation(image, percent);    UIImage *newImage = [UIImage imageWithData:imageData];    return newImage;}

percent

比例,比例的话,如果你要求图片小于1M,而图片大小比1M大,那么比例你可以用

1M / 图片的大小

即:ONEM/imageData.length


2.判断图片格式

  if (UIImagePNGRepresentation(image) == nil) {   image_fileType = @"JPEG";}else { image_fileType = @"PNG";}


1 0
原创粉丝点击