如何在.jpg中将.jpg图像保存为.png或.jpeg

时间:2011-02-09 10:04:37

标签: ios4

我正在我的文档目录中保存图像..我没有.png或.jpeg图像的问题。我能够在iphone中正确显示它们。但是来到.jpg,我无法显示。请帮助我。提前了解

+(void)DownloadImage:(NSString*)ImagePath{

if ([ImagePath isEqualToString:@""]) {
    return;
}

UIImage *dimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://1xyz/uploads/%@",ImagePath]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"pathIMAGEPATHS:::::::%@",ImagePath);
NSLog(@"path:::::::%@",docDir);
NSArray *patharr=[ImagePath componentsSeparatedByString:@"."];
NSString* Ext=[NSString stringWithFormat: @"%@",[patharr objectAtIndex:1]];
NSString *FilePath = [NSString stringWithFormat: [NSString stringWithFormat:@"%@/%@",docDir,ImagePath]];
NSLog(@"%@/%@",docDir,ImagePath);
if([Ext isEqualToString:@"png"])
{
    NSLog(@"saving png");
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
    [data1 writeToFile:FilePath atomically:YES];
}
else if([Ext isEqualToString:@"jpeg"])
{
    NSLog(@"saving jpeg");
    NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(dimage, 1.0f)];//1.0f = 100% quality
    [data2 writeToFile:FilePath atomically:YES];
}
else 
{
    NSData *data3 = [NSData dataWithData:UIImageJPEGRepresentation(dimage, 1.0f)];
    [data3 writeToFile:FilePath atomically:YES];

}
NSLog(@"saving image done");

[dimage release];

}

1 个答案:

答案 0 :(得分:0)

您可以使用UIImagePNGRepresentation。首先使用原始JPG创建UIImage,然后使用此类方法将其另存为PNG。

UIImage *image = [UIImage imageNamed:@"yourImage.jpg"]
NSData *imageData = UIImagePNGRepresentation(image);

获得数据后,您可以致电writeToURL:保存到磁盘。