gpt4 book ai didi

iphone - 检测具有透明背景的 UIImage 的裁剪矩形

转载 作者:可可西里 更新时间:2023-11-01 04:39:53 28 4
gpt4 key购买 nike

获取具有透明背景的 UIImage 并确定要裁剪到的最小矩形以便只留下可见图像数据(当然,如果图像数据不是矩形,则还有额外的透明背景)的策略是什么?

我找到了很多关于将 UIImage 裁剪为 CGRect 的信息,大量需要用户干预的裁剪 View Controller ,以及几个带有图像处理类和类别的开源库(包括 MGImageUtilities 和 NYXImagesKit),但还没有解决问题我的特殊问题。

我当前的应用程序针对 iOS 5.0,因此与它的兼容性将是最佳的。

编辑:顺便说一句,我希望有一种比蛮力更好的方法,即在最坏的情况下,在行和列中的图像数据中寻找边缘边界的情况下查看每个像素。

最佳答案

你有没有机会看到https://gist.github.com/spinogrizz/3549921

看起来这正是您所需要的。

只是为了不丢失,从那个页面复制粘贴:

- (UIImage *) imageByTrimmingTransparentPixels {
int rows = self.size.height;
int cols = self.size.width;
int bytesPerRow = cols*sizeof(uint8_t);

if ( rows < 2 || cols < 2 ) {
return self;
}

//allocate array to hold alpha channel
uint8_t *bitmapData = calloc(rows*cols, sizeof(uint8_t));

//create alpha-only bitmap context
CGContextRef contextRef = CGBitmapContextCreate(bitmapData, cols, rows, 8, bytesPerRow, NULL, kCGImageAlphaOnly);

//draw our image on that context
CGImageRef cgImage = self.CGImage;
CGRect rect = CGRectMake(0, 0, cols, rows);
CGContextDrawImage(contextRef, rect, cgImage);

//summ all non-transparent pixels in every row and every column
uint16_t *rowSum = calloc(rows, sizeof(uint16_t));
uint16_t *colSum = calloc(cols, sizeof(uint16_t));

//enumerate through all pixels
for ( int row = 0; row < rows; row++) {
for ( int col = 0; col < cols; col++)
{
if ( bitmapData[row*bytesPerRow + col] ) { //found non-transparent pixel
rowSum[row]++;
colSum[col]++;
}
}
}

//initialize crop insets and enumerate cols/rows arrays until we find non-empty columns or row
UIEdgeInsets crop = UIEdgeInsetsMake(0, 0, 0, 0);

for ( int i = 0; i<rows; i++ ) { //top
if ( rowSum[i] > 0 ) {
crop.top = i; break;
}
}

for ( int i = rows; i >= 0; i-- ) { //bottom
if ( rowSum[i] > 0 ) {
crop.bottom = MAX(0, rows-i-1); break;
}
}

for ( int i = 0; i<cols; i++ ) { //left
if ( colSum[i] > 0 ) {
crop.left = i; break;
}
}

for ( int i = cols; i >= 0; i-- ) { //right
if ( colSum[i] > 0 ) {
crop.right = MAX(0, cols-i-1); break;
}
}

free(bitmapData);
free(colSum);
free(rowSum);

if ( crop.top == 0 && crop.bottom == 0 && crop.left == 0 && crop.right == 0 ) {
//no cropping needed
return self;
}
else {
//calculate new crop bounds
rect.origin.x += crop.left;
rect.origin.y += crop.top;
rect.size.width -= crop.left + crop.right;
rect.size.height -= crop.top + crop.bottom;

//crop it
CGImageRef newImage = CGImageCreateWithImageInRect(cgImage, rect);

//convert back to UIImage
return [UIImage imageWithCGImage:newImage];
}
}

关于iphone - 检测具有透明背景的 UIImage 的裁剪矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16569251/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com