【问题标题】:Saving UIGraphicsContext image as .png instead of .jpg将 UIGraphicsContext 图像保存为 .png 而不是 .jpg
【发布时间】:2015-02-07 19:02:11
【问题描述】:

我有这段代码可以将我的图像调整为缩略图:

//MAKE THUMBNAIL

    CGSize origImageSize = chosenImage.size;

    //the rectangle of the thumbnail;
    CGRect newRect = CGRectMake(0, 0, 70, 70);

    //scaling ratio
    float ratio = MAX(newRect.size.width/origImageSize.width, newRect.size.height/origImageSize.height);


    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);


    CGRect projectRect;
    projectRect.size.width= ratio*origImageSize.width;
    projectRect.size.height=ratio*origImageSize.height;
    //center the image
    projectRect.origin.x= ((newRect.size.width-projectRect.size.width)/2);
    projectRect.origin.y=((newRect.size.height-projectRect.size.height)/2);
    [chosenImage drawInRect:projectRect];

    //get the image from the image context
    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    self.thumbnailView.image=smallImage;

    UIImageWriteToSavedPhotosAlbum(smallImage, self, nil, nil); //20kb
    UIGraphicsEndImageContext();

它将图像保存为jpg,无论如何我可以将其保存为png吗?谢谢

【问题讨论】:

    标签: ios xcode uiimage uigraphicscontext


    【解决方案1】:

    尝试将图像的数据转换为 PNG 数据表示,然后再转换回 PNG 图像,例如:

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    NSData *pngImageData =  UIImagePNGRepresentation(smallImage);
    UIImage *pngSmallImage = [UIImage imageWithData:pngImageData];
    UIImageWriteToSavedPhotosAlbum(pngSmallImage, self, nil, nil); //20kb
    UIGraphicsEndImageContext();
    

    【讨论】:

    • 这样做会降低图像质量吗?将图像存储为 png 更好还是没有太大区别?
    • @Kex 对此表示怀疑。 PNG 支持无损数据压缩。
    相关资源