目标c iPhone UIImage转换为PNG PPI / DPI太高

时间:2012-11-21 09:31:39

标签: objective-c uiimage png dpi ppi

我正在生成一个UIImage:

//scale UIView size to match underlying UIImage size
float scaleFactor = 10.0

UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, scaleFactor);

[self.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

UIImage的大小为3200x2400,这就是我想要的。但是,当我转换为PNG格式以作为电子邮件附件发送时:

NSData* data = UIImagePNGRepresentation(image);

MFMailComposeViewController* controller;
...
[controller addAttachmentData:data mimeType:mimeType fileName:.fileName];

我最终得到的图像是720 ppi,因此~12.8mb。这太大了。

我不知道720 ppi的来源,UIImage是从72 ppi的图像生成的。它必须与之相关:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque,scaleFactor);

我需要根据底层的UIImage(比UIView的边界大得多)从UIView创建一个UIImage,但是我需要保持原始的ppi。 720 ppi对于电子邮件附件来说太不切实际了。

有什么想法?

3 个答案:

答案 0 :(得分:3)

scaleFactor too high results large image data DecreasescaleFactor float scaleFactor = 1.0; 然后截屏。

基本上它应该是

 NSData *imageData = UIImagePNGRepresentation(imagehere);

转换为PNG,如:

 UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 1.0);
 [yourimageview.image drawInRect:CGRectMake(0,0,self.bounds.size)];
 UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

将imageData附加到邮件。

编辑:像这样调整图片大小:

{{1}}

答案 1 :(得分:1)

根据eagle.dan.1349的建议,我尝试了以下内容:

-(UIImage*)convertViewToImage
{
    UIImage* retVal = nil;

    //create the graphics context
    CGSize imageSize = targetImage.size;
    CGSize viewSize = self.bounds.size;

    //CGSize cvtSize = CGSizeMake(imageSize.width/viewSize.width,            imageSize.height/viewSize.height);
    float scale = imageSize.width/viewSize.width;

    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, scale);

    //write the contents of this view into the context
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];

    //get the image
    retVal = UIGraphicsGetImageFromCurrentImageContext();

    //close the graphics context
    UIGraphicsEndImageContext();

    NSData* data = UIImageJPEGRepresentation(retVal, 0.0);
    [retVal release];
    retVal = [UIImage imageWithData:data];

    return retVal;
}

*稍后我执行:

NSData* data = UIImagePNGRepresentation(image);

然而,正如我所提到的,这仍然会产生5.8 MB的图像,所以我怀疑在300 ppi附近的某处。

我需要一个UIVmage,由UIView创建,具有我要求的分辨率和大小(72 ppi,3200X2400)。必须有办法做到这一点。

答案 2 :(得分:0)

冷杉,我想知道你的设备如何不会因这些高清图像的流泪而哭泣。当我从事与图像相关的项目时,PNG中的这种高分辨率在社交网络共享和电子邮件发送方面造成了很多问题,所以我们转向了JPEG。 此外,一般不建议在PNG上在网上发送图像,最好通过适当的压缩使其成为JPEG。 但是,如果您需要使用PNG,您可以制作这种技巧:首先将其转换为JPEG数据,使用此数据初始化您的图像,然后将其转换为PNG。

编辑:此外,尝试设置您需要的上下文大小为320X240并且不要缩放到10,而是设置为0以便系统确定所需的比例。它可能有所帮助。然后再次缩放您生成的UIImage。

相关问题