代码之家  ›  专栏  ›  技术社区  ›  cduck Daniel

如何降低iPhone objective-c中的图像质量/大小?

  •  12
  • cduck Daniel  · 技术社区  · 16 年前

    我有一个应用程序,可以让用户用iPhone拍照,并将其用作应用程序的背景图像。我用 UIImagePickerController UIImageView UIImage 对象

    IBOutlet UIImageView *backgroundView;
    
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
     backgroundView.image = image;
     [self dismissModalViewControllerAnimated:YES];
    }
    

    我怎样才能缩小尺寸 到480x320以便我的应用程序能够节省内存? 我不在乎是否有图像质量问题。

    提前谢谢。

    3 回复  |  直到 13 年前
        1
  •  16
  •   Ben Gottlieb    16 年前

    可以创建图形上下文,以所需比例将图像绘制到其中,然后使用返回的图像。例如:

    UIGraphicsBeginImageContext(CGSizeMake(480,320));
    
    CGContextRef            context = UIGraphicsGetCurrentContext();
    
    [image drawInRect: CGRectMake(0, 0, 480, 320)];
    
    UIImage        *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();    
    
        2
  •  15
  •   Kai    14 年前

    我知道这个问题已经解决了,但是如果有人(像我一样)想要缩放图像以保持纵横比,下面的代码可能会有所帮助:

    -(UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)size
    {
        float width = size.width;
        float height = size.height;
    
        UIGraphicsBeginImageContext(size);
        CGRect rect = CGRectMake(0, 0, width, height);
    
        float widthRatio = image.size.width / width;
        float heightRatio = image.size.height / height; 
        float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;
    
        width = image.size.width / divisor; 
        height = image.size.height / divisor;
    
        rect.size.width  = width;
        rect.size.height = height;
    
        if(height < width)
            rect.origin.y = height / 3;
    
        [image drawInRect: rect];
    
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();   
    
        return smallImage;
    }
    
        3
  •  3
  •   roydell Clarke    15 年前

    不要问我为什么。苹果告诉我的。