ios 工具類系列—–圖片處理–imageUtil

來源:互聯網
上載者:User
============================================================博文原創,轉載請聲明出處電子咖啡(原id藍岩)============================================================

ios開發中需要用到不少的工具類,這裡記錄一下,可能會不完美,後續會不斷的更新,也希望大家能分享自己好的工具。

Imageutil.h 可以從相簿中選取映像,並且剪裁為指定大小儲存到本地:

Imageutil.h

////  Imageutil.h//#import <Foundation/Foundation.h>#import "NSData+Base64.h"@protocol ImageutilDelegate <NSObject>@required-(void)didFinishPickingMedia;@end@interface Imageutil : NSObject<UINavigationControllerDelegate, UIImagePickerControllerDelegate>@property (retain,nonatomic) UIViewController<ImageutilDelegate>* viewcontroller;@property (retain,nonatomic) NSString* imageName;-(Imageutil*)initWithViewController:(UIViewController<ImageutilDelegate>*)viewcontroller_ imageName:(NSString*)imageName_;-(void)selectImage;+(UIImage*)getImageByName:(NSString*)imageName;+ (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imagen;- (UIImage*) scalingAndCroppingToSize:(CGSize)targetSize withImage:(UIImage*)sourceImage;@end

Imageutil.m

////  Imageutil.m//  Yunho2////  Created by l on 12-11-5.////#import "Imageutil.h"#define IMAGE_TYPE @"portrait"@implementation Imageutil{    }@synthesize viewcontroller;@synthesize imageName;-(Imageutil*)initWithViewController:(UIViewController<ImageutilDelegate>*)viewcontroller_ imageName:(NSString*)imageName_{    if ((self=[super init]) !=nil) {        self.viewcontroller=viewcontroller_;        self.imageName=imageName_;        return self;    }    return nil;}-(void)selectImage{    UIImagePickerController *imagePicker = [[[UIImagePickerController alloc] init]autorelease];    imagePicker.delegate = self;    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;    imagePicker.allowsEditing = YES;        [viewcontroller presentModalViewController:imagePicker animated:YES];}+ (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imagen{    NSData* imageData = UIImagePNGRepresentation(tempImage);    NSString* documentsDirectory = [Imageutil getDocumentFolderPath];    // Now we get the full path to the file and then we write it out    NSString* imageDirPath=[documentsDirectory stringByAppendingPathComponent:IMAGE_TYPE];    NSFileManager *manager = [NSFileManager defaultManager];        if ([manager fileExistsAtPath:imageDirPath]==NO) {        [manager createDirectoryAtPath:imageDirPath withIntermediateDirectories:YES attributes:nil error:nil];    }    [imageData writeToFile:[imageDirPath stringByAppendingPathComponent:imagen               ] atomically:NO];}+ (NSString *)getDocumentFolderPath{    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    return [paths objectAtIndex:0];}- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];    UIImage* scaledImage=[self scalingAndCroppingToSize:CGSizeMake(64, 64) withImage:image];    [Imageutil saveImage:scaledImage WithName:imageName];    [viewcontroller dismissModalViewControllerAnimated:YES];    [viewcontroller didFinishPickingMedia];}+(UIImage*)getImageByName:(NSString*)imageName{    if (imageName==nil || [@"" isEqualToString:imageName]) {        return nil;    }    NSString* documentsDirectory = [Imageutil getDocumentFolderPath];    NSString* imagePath=[documentsDirectory stringByAppendingPathComponent:IMAGE_TYPE];    return [UIImage imageWithContentsOfFile:[imagePath stringByAppendingPathComponent:imageName]];}//剪裁&壓縮圖片- (UIImage*) scalingAndCroppingToSize:(CGSize)targetSize withImage:(UIImage*)sourceImage{    UIImage *newImage = nil;    CGSize imageSize = sourceImage.size;    CGFloat width = imageSize.width;    CGFloat height = imageSize.height;    CGFloat targetWidth = targetSize.width;    CGFloat targetHeight = targetSize.height;    CGFloat scaleFactor = 0.0;    CGFloat scaledWidth = targetWidth;    CGFloat scaledHeight = targetHeight;    //修剪點的位置,以3*2長方形剪裁為2*2正方形為例,截取image中心部分,剪下點為(0,0.5)    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);        if (CGSizeEqualToSize(imageSize, targetSize) == NO)    {        //compress scale        CGFloat widthFactor = targetWidth / width;        CGFloat heightFactor = targetHeight / height;                //set scaleFactoras lesser scale,fit lesser scale        if (widthFactor > heightFactor)            scaleFactor = widthFactor; // scale to fit height        else            scaleFactor = heightFactor; // scale to fit width                //reset the target size with the new scale factor        scaledWidth  = width * scaleFactor;        scaledHeight = height * scaleFactor;                // get cropping point        if (widthFactor > heightFactor)        {            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;        }        else if (widthFactor < heightFactor)        {            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;        }    }        UIGraphicsBeginImageContext(targetSize); // this will crop        CGRect thumbnailRect = CGRectZero;    thumbnailRect.origin = thumbnailPoint;    thumbnailRect.size.width  = scaledWidth;    thumbnailRect.size.height = scaledHeight;        //corpping image to special rectangle    [sourceImage drawInRect:thumbnailRect];        newImage = UIGraphicsGetImageFromCurrentImageContext();    if(newImage == nil)        NSLog(@"could not scale image");        //pop the context to get back to the default    UIGraphicsEndImageContext();    return newImage;}-(void)dealloc{    [super dealloc];    [viewcontroller release];    [imageName release];}@end

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.