首页 > 其他 > 详细

压缩图片操作和生成圆形图片

时间:2014-07-31 09:42:16      阅读:571      评论:0      收藏:0      [点我收藏+]

1.对本地相册库或相机拍摄下来的图片进行压缩处理,传进来的参数分别有:要压缩的图片和压缩后的大小。

//压缩图片
+ (UIImage*)imageWithImageSimple:(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;
}

2.将图片压缩转为NSData写入沙盒。压缩后以NSData上传图片。

//sdk中提供了方法可以直接调用 

UIImage *img = [UIImage imageNamed:@"some.png"];

NSData *dataObj = UIImageJPEGRepresentation(img, 1.0);  

 

//下面是sdk中UIImage.h头文件中的内容 

UIKIT_EXTERN NSData *UIImagePNGRepresentation(UIImage *image);

 // return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format 

UIKIT_EXTERN NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);

  // return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)

JPEG的转换方法里面第二个参数是压缩系数,可以有效的减小图片的大小。UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多。项目中做图片上传之前,经过测试同一张拍照所得照片png大小在8M,而JPG压缩系数为0.75时候,大小只有1M。而且,将压缩系数降低对图片视觉上并没有太大的影响。

保存图片到沙盒

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}

上传图片

- (void)putImagewithImage:(UIImage *)image
{
    //上传图片
    ASIHTTPRequest *requst = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:UPLOADURL]];
    [requst setRequestMethod:@"PUT"];
    NSData *data = UIImagePNGRepresentation(image);
    if (data == nil) {
        data = UIImageJPEGRepresentation(image, 0.1);
    }
    [requst appendPostData:data];
    [requst startAsynchronous];
    [self showLoading:YES];
    requst.delegate = self;
}

当然也可以用表单的形式上传图片

转自:http://blog.csdn.net/decemberd/article/details/8629996

3.生成固定大小的圆形图片

//2.保持原来的长宽比,生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image)
    {
        newimage = nil;
    }
    else
    {
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height)
        {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else
        {
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

最后是调用了

 UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件

----------------------------------------------------Demo----------------------------------

#import <MobileCoreServices/MobileCoreServices.h>

- (void)viewDidLoad
{
     _tableHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,100,100)];
    _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake((250-100)/2,10, 60, 60)];
    _headImageView.backgroundColor = [UIColor blackColor];
    _headImageView.image = [UIImage imageNamed:@"slide_Login"];
    _headImageView.userInteractionEnabled = YES;
    _headImageView.layer.cornerRadius = 30;
    _headImageView.layer.masksToBounds = YES;
    [_tableHeadView addSubview:_headImageView];
    [_headImageView release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeImageAction:)];
    [_headImageView addGestureRecognizer:tap];
    [tap release];
}            

/**
 *  选择图片方法
 *
 *  @param sender <#sender description#>
 */
-(void)changeImageAction:(UITapGestureRecognizer *)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择文件来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"摄像机",@"本地相册",nil];
    [actionSheet showInView:self.view];
}

#pragma mark -UIActionSheetDelegate Methods
-(void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://照相机
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = self;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePicker animated:YES completion:^{
                    
                }];
            }
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"设备不支持摄像头" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alertView show];
            }
            break;
        }
        case 1://摄像机
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = self;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePicker.videoQuality = UIImagePickerControllerQualityTypeLow;
                [self presentViewController:imagePicker animated:YES completion:^{
                    
                }];
            }
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"设备不支持摄像头" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alertView show];
            }
            break;
        }
        case 2://本地相册
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePicker animated:YES completion:^{
                
            }];
            break;
        }
        
        default:
            break;
    }
}

#pragma mark -UIImagePickerControllerDelegate Method
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType]
         isEqualToString:(__bridge NSString *)kUTTypeImage])//等到图片
    {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    else if ([[info objectForKey:UIImagePickerControllerMediaType]
              isEqualToString:(__bridge NSString *)kUTTypeMovie])//得到视频的数据
    {
        NSString *videoPath = (__bridge NSString *)[[info objectForKey:UIImagePickerControllerMediaURL] path];
        NSData *fileData = [NSData dataWithContentsOfFile:videoPath];
    }
    else{}
    [picker  dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker  dismissViewControllerAnimated:YES completion:^{
        
    }];
}
/**
 *  保存图片
 *
 *  @param img <#img description#>
 */
-(void)saveImage:(UIImage *)image
{
    NSString *imageFilePath = [self getImageFilePath];
    NSFileManager *fileManger  = [NSFileManager defaultManager];
    BOOL success = [fileManger fileExistsAtPath:imageFilePath];
    NSError *error;
    if (success)
    {
        success = [fileManger removeItemAtPath:imageFilePath error:&error];//删除原图片
    }
    
    //尺寸改为60*60
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(60, 60)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    _headImageView.image = selfPhoto;
}
/**
 *  获取图片文件路径
 *
 *  @return <#return value description#>
 */
-(NSString *)getImageFilePath
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *imageFilePath = [path stringByAppendingPathComponent:@"selfPhone.jpg"];
    return imageFilePath;
    
}

//2.保持原来的长宽比,生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image)
    {
        newimage = nil;
    }
    else
    {
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height)
        {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else
        {
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

.

 

压缩图片操作和生成圆形图片,布布扣,bubuko.com

压缩图片操作和生成圆形图片

原文:http://www.cnblogs.com/huen/p/3860639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!