//保存图片
-
(void )saveImage:(NSImage *)image imageName:(NSString *)name{
[image lockFocus];
//先设置 下面一个实例
NSBitmapImageRep *bits = [[NSBitmapImageRep alloc]initWithFocusedViewRect:NSMakeRect(0, 0, image.size.width, image.size.height)];//138.32为图片的长和宽
[image unlockFocus];
//再设置后面要用到得 props属性
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:0] forKey:NSImageCompressionFactor];
//之后 转化为NSData 以便存到文件中
NSData *imageData = [bits representationUsingType:NSPNGFileType properties:imageProps];
//设定好文件路径后进行存储就ok了 /Users/mjt/Pictures
NSString *path = [NSString stringWithFormat:@"~/Pictures/%@.png",name];
BOOL isSuccess = [imageData writeToFile:[[NSString stringWithString:path] stringByExpandingTildeInPath]atomically:YES]; //保存的文件路径一定要是绝对路径,相对路径不行
NSLog(@"Save Image: %d", isSuccess);
// NSImage *imag = [[NSImage alloc] initWithContentsOfFile:path];
// NSImageView *iamgview = [NSImageView imageViewWithImage:image];
// [self.bgView addSubview:iamgview];
// iamgview.frame = NSMakeRect(0, 0, 400, 300);
}
// 等比缩放 -
(NSImage)resizeImage2:(NSImage)sourceImage forSize:(CGSize)targetSize {
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;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;// scale to fit the longer scaleFactor = (widthFactor>heightFactor)?widthFactor:heightFactor; scaledWidth = ceil(width * scaleFactor); scaledHeight = ceil(height * scaleFactor); // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; }
}
NSImage *newImage = [[NSImage alloc] initWithSize:NSMakeSize(scaledWidth, scaledHeight)];
CGRect thumbnailRect = {thumbnailPoint, {scaledWidth, scaledHeight}};
NSRect imageRect = NSMakeRect(0.0, 0.0, width, height);[newImage lockFocus];
[sourceImage drawInRect:thumbnailRect fromRect:imageRect operation:NSCompositeCopy fraction:1.0];
[newImage unlockFocus];return newImage;
}
网友评论