resize an UIImage and save it on my app file syste

2019-05-30 09:31发布

I need to resize an UIImage and save it on my app file system,

I can resize the image

or just show it with a smaller cgrect for the frame,

but how can i save this newly resized image on my app file sys?

thanks!

2条回答
成全新的幸福
2楼-- · 2019-05-30 10:03

Assuming your image is called image

//Where the 0 denotes the compression (0 to 1).
NSData *imageData = UIImageJPEGRepresentation(image, 0);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyImageFolder"];

NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", imageName]]; //add our image to the path

bool successI = [imageData writeToFile:fullPath atomically:YES];
if (successI) {
    //        NSLog(@"Image saved correctly");
} else
    NSLog(@"Error while saving Image");

Forgot to mention, you can change the

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

to save it somewhere else.

查看更多
Fickle 薄情
3楼-- · 2019-05-30 10:26

You can first convert the UIImage to NSData by

UIImageJPEGRepresentation

or

UIImagePNGRepresentation

Then write the data to Document or Library folder in your app.

查看更多
登录 后发表回答