iOS項目中幾個常用的圖片處理方法

第一個:壓縮圖片

當我們上傳圖片到服務器時,需要壓縮一下圖片的質量。方法如下:

/*
 *壓縮圖片
 */
+ (UIImage *)resizeImageWithImage:(UIImage *)image targetSize:(CGSize)targetSize;

+ (UIImage *)resizeImageWithImage:(UIImage *)image targetSize:(CGSize)targetSize
{
    CGSize size = image.size;
    CGFloat widthRatio = targetSize.width / image.size.width;
    CGFloat heightRatio = targetSize.height / image.size.height;
    CGSize newSize;
    if (widthRatio > heightRatio) newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio);
    else newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio);
    CGRect rect = CGRectMake(0, 0, newSize.width, newSize.height);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    [image drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

第二個,截取人臉部圖片

拍攝身份證或者其他有人臉部的圖片時,我們可能只需要人臉部分的頭像圖片。裁剪的方法如下:

/*
 *獲取臉部圖片
 */
+ (CGRect)adjustFaceImageWithRect:(CGRect)rect sourceImage:(UIImage *)sourceImage;
+ (CGRect)adjustFaceImageWithRect:(CGRect)rect sourceImage:(UIImage *)sourceImage
{
    CGRect faceRect;
    CGFloat widthMargin = rect.size.width/2;;
    CGFloat heightMargin = rect.size.height/2;
    faceRect.origin.x = MAX(rect.origin.x - widthMargin, 0);
    faceRect.origin.y = MAX(rect.origin.y - heightMargin - heightMargin/2, 0) + 20;
    faceRect.size.width = MIN(rect.size.width + 2*widthMargin, (CGFloat)(sourceImage.size.width - faceRect.origin.x - 1));
    faceRect.size.height = MIN(rect.size.height + 2*heightMargin + heightMargin/2, (CGFloat)(sourceImage.size.height - faceRect.origin.y - 1));
    return faceRect;
}
第三個,從一張圖片上截取一部分圖片

根據坐標信息,從一張大的圖片上裁剪出我們需要的那一部分圖片區域,具體如下:

/*
 *在一張圖片上根據坐標范圍裁剪圖片
 */
+ (UIImage *)cutImageWithRect:(CGRect)rect image:(UIImage *)cutImage;
+ (UIImage *)cutImageWithRect:(CGRect)rect image:(UIImage *)cutImage
{
    CGImageRef cgRef = cutImage.CGImage;
    CGImageRef imageRef = CGImageCreateWithImageInRect(cgRef, rect);
    UIImage *thumbScale = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return thumbScale;
}
第四個,保存圖片到本地
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL) msg = @"保存圖片失敗" ;
    else              msg = @"保存圖片成功" ;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"確定"
                                          otherButtonTitles:nil];
    [alert show];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容