您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 將圖片切割成小圖的方法

編輯:iOS 開發綜合

在 iOS 或 macOS 圖片處理中,有時需要將一張大圖切割成多張小圖。核心概念是計算切割後的行列數,再透過 CGImageCreateWithImageInRect 擷取每個區域。

1. 載入圖片並取得尺寸

可先載入圖片,取得寬高與 CGImage:

NSImage *image = [[NSImage alloc] initWithContentsOfFile:inputFile];
NSSize size = [image size];

NSArray *representations = [image representations];
if ([representations count]) {
    NSBitmapImageRep *representation = representations[0];
    size.width = [representation pixelsWide];
    size.height = [representation pixelsHigh];
}

2. 計算切割數量

若每张小圖尺寸為 titleSize,可計算行數與列數:

CGFloat titleSize = 256;
NSInteger rows = (NSInteger)ceil(size.height / titleSize);
NSInteger cols = (NSInteger)ceil(size.width / titleSize);

3. 切割並輸出

for (int y = 0; y != rows; y++) {
    for (int x = 0; x != cols; x++) {
        CGRect titleRect = CGRectMake(x * titleSize, y * titleSize, titleSize, titleSize);
        CGImageRef titleImage = CGImageCreateWithImageInRect(imageRef, titleRect);

        NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:titleImage];
        NSData *data = [imageRep representationUsingType:NSJPEGFileType properties:nil];
        CGImageRelease(titleImage);

        NSString *path = [outputPath stringByAppendingFormat:@"_%02i_%02i.jpg", x, y];
        [data writeToFile:path atomically:NO];
    }
}

4. 注意事項

切割時要注意最後一張小圖可能不完整,因為原圖尺寸未必能被 titleSize 整除。若需要固定尺寸,可先縮放或裁切原圖。此外,CGImageCreateWithImageInRect 建立後,若不再使用,應呼叫 CGImageRelease 釋放。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved