在 iOS 或 macOS 圖片處理中,有時需要將一張大圖切割成多張小圖。核心概念是計算切割後的行列數,再透過 CGImageCreateWithImageInRect 擷取每個區域。
可先載入圖片,取得寬高與 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];
}
若每张小圖尺寸為 titleSize,可計算行數與列數:
CGFloat titleSize = 256;
NSInteger rows = (NSInteger)ceil(size.height / titleSize);
NSInteger cols = (NSInteger)ceil(size.width / titleSize);
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];
}
}
切割時要注意最後一張小圖可能不完整,因為原圖尺寸未必能被 titleSize 整除。若需要固定尺寸,可先縮放或裁切原圖。此外,CGImageCreateWithImageInRect 建立後,若不再使用,應呼叫 CGImageRelease 釋放。