如果有人能帮我解决图像保存问题,我将不胜感激。 我有一个应用程序,其中包含带有相应图像的食谱。我需要调整它们的大小以保留内存并使我的应用程序更加健壮。一切看起来都不错,UIImage有适当的尺寸。但是当我将这个图像保存到文档时,它似乎变得比应该的大两倍。
我用于图像大小调整的代码:
+(UIImage *) createImageFromImage: (UIImage *)image WithName:(NSString *)name Thumbnail: (BOOL)isThumbnail{
CGSize oldSize = image.size;
CGSize newSize;
CGFloat scaleFactor;
if (isThumbnail) {
name = [NSString stringWithFormat:@"t_%@", name];
newSize = CGSizeMake(125, 92);
}
else{
newSize = CGSizeMake(320, 240);
}
if (!CGSizeEqualToSize(newSize, oldSize)) {
CGFloat widthFactor = newSize.width/oldSize.width;
CGFloat heightFactor = newSize.height/oldSize.height;
if (((widthFactor > heightFactor)||(heightFactor > 1))&&(widthFactor < 1)) {
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
newSize.width = scaleFactor*oldSize.width;
newSize.height = scaleFactor*oldSize.height;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *newImage = nil;
newImage = [self drawImage:image InContextWithSize:newSize];
[UIImagePNGRepresentation(newImage) writeToFile:path atomically:YES];
return newImage;
}
+(UIImage *)drawImage: (UIImage *)image InContextWithSize: (CGSize) newSize {
UIImage *newImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
答案 0 :(得分:1)
我刚刚更改了几行代码来获取scaleFactor
-(UIImage *) createImageFromImage: (UIImage *)image WithName:(NSString *)name Thumbnail: (BOOL)isThumbnail{
CGSize oldSize = image.size;
CGSize newSize;
CGFloat scaleFactorForWidth = 0.0,scaleFactorForHeight= 0.0;
if (isThumbnail) {
name = [NSString stringWithFormat:@"t_%@", name];
newSize = CGSizeMake(125, 92);
}
else{
newSize = CGSizeMake(320, 240);
}
if (!CGSizeEqualToSize(newSize, oldSize)) {
CGFloat widthFactor = newSize.width/oldSize.width;
CGFloat heightFactor = newSize.height/oldSize.height;
if (widthFactor != 1) {
scaleFactorForWidth = widthFactor;
newSize.width = scaleFactorForWidth*oldSize.width;
}
if (heightFactor != 1) {
scaleFactorForHeight = heightFactor;
newSize.height = scaleFactorForHeight*oldSize.height;
}
}
NSLog(@"New Size : (%f,%f)",newSize.width,newSize.height);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *newImage = nil;
newImage = [self drawImage:image InContextWithSize:newSize];
[UIImagePNGRepresentation(newImage) writeToFile:path atomically:YES];
return newImage;
}
答案 1 :(得分:1)
这个问题似乎与标准的Xcode PNG压缩选项有关。如果他不想发生这种情况,只需要将其设置为NO即可。我想这是为了视网膜显示而制作的。