目标:
在仅包含黑色和透明像素的图像左侧找到第一个黑色像素。
我有什么:
我知道如何获取像素数据并拥有一个黑色和透明像素数组(在此处找到:https://stackoverflow.com/a/1262893/358480):
+ (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy count:(int)count
{
NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];
// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
for (int ii = 0 ; ii < count ; ++ii)
{
NSUInteger alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;
[result addObject:[NSNumber numberWithInt:alpha]];
}
free(rawData);
return result;
}
问题是什么?
我无法理解函数“扫描”图像的顺序。
我想要的是仅获取图像的列并找到列表中具有非透明像素的第一列。这样我就知道如何裁剪图像的左侧透明边了?
如何按列获取像素?
谢谢
沙尼
最佳答案
字节按从左到右、从上到下的顺序排列。所以为了做你想做的事,我想你想像这样遍历 rawData
:
int x = 0;
int y = 0;
BOOL found = NO;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
unsigned char alphaByte = rawData[(y*bytesPerRow)+(x*bytesPerPixel)+3];
if (alphaByte > 0) {
found = YES;
break;
}
}
if (found) break;
}
NSLog(@"First non-transparent pixel at %i, %i", x, y);
那么包含非透明像素的第一列将是 x
列。
关于ios - 图像像素数据 "scans"如何得到图像像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8698930/