简体   繁体   中英

iOS - save image in jpg format

My question is what format the image is saved, if is dat or jpg. This is the code that i used:

    NSString * urlImage = .....;
    NSString * _folderPath = .....;

    NSString * imageName = [[urlImage componentsSeparatedByString:@"/"] lastObject];
        NSString * jpegPath = [NSString stringWithFormat:@"%@%@",_folderPath,imageName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:jpegPath])
        {
            NSURL *url = [NSURL URLWithString:urlImage];
            //Download image
            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];

            //Save image
            NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
            [data writeToFile:jpegPath atomically:YES];
        }

Following is piece of code for save .jpg image

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path =  [docs stringByAppendingFormat:@"/image1.jpg"];

NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageView.image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];

You should use

stringByAppendingPathComponent method to create or get exact valid path

Use this way:

    NSString * jpegPath = [_folderPath stringByAppendingPathComponent:imageName];// [NSString stringWithFormat:@"%@%@",_folderPath,imageName];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM