IOS中修改圖片的大小:修改分辨率和裁剪

cg4f 9年前發布 | 3K 次閱讀 Objective-C IOS

在IOS開發中,經常有限制圖片文件大小的,有的用戶圖片很大,導致上傳時間慢,造成問題。

如:微信分享中,如果圖片的大小好像大于50kbytes,就分享失敗,而且沒有任何提示。

所以,我添加了兩個函數:

一、修改當前圖片的大小,newSize是新的size尺寸,這個方法幫助用戶獲取到更小的圖片。

但是這個newSize的尺寸建議跟原圖一樣,不然圖片就變形了。

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize

{

    // Create a graphics image context

    UIGraphicsBeginImageContext(newSize);

    

    // Tell the old image to draw in this new context, with the desired

    // new size

    [image drawInRect:CGRectMake(,,newSize.width,newSize.height)];

    

    // Get the new image from the context

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    

    // End the context

    UIGraphicsEndImageContext();

    

    // Return the new image.

    return newImage;

}

二、截圖功能,實現用戶想要截取圖的RECT

- (UIImage *)getImageByCuttingImage:(UIImage *)image Rect:(CGRect)rect{

    //大圖bigImage

    //定義myImageRect,截圖的區域

    CGRect myImageRect = rect;

    UIImage* bigImage= image;

    CGImageRef imageRef = bigImage.CGImage;

    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);

    CGSize size;

    size.width = rect.size.width;

    size.height = rect.size.height;

    UIGraphicsBeginImageContext(size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextDrawImage(context, myImageRect, subImageRef);

    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];

    UIGraphicsEndImageContext();

    return smallImage;

}


 本文由用戶 cg4f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!