iOS - 以jpg格式保存图像

时间:2014-02-10 12:46:28

标签: ios objective-c image

我的问题是图像保存的格式,如果是dat或jpg。这是我使用的代码:

    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];
        }

2 个答案:

答案 0 :(得分:4)

以下是保存 .jpg 图片

的代码段
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];

答案 1 :(得分:0)

你应该使用

stringByAppendingPathComponent方法来创建或获取完全有效的路径

使用这种方式:

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