检测图像周围的单色帧以进行修剪

时间:2014-02-27 18:59:47

标签: ios objective-c cocoa-touch imaging

我的图像周围有白色边框。我想在运行时摆脱那个边界。

一个简单但很慢的算法就是这样:

  1. 从上到下扫描每一行,如果行中的像素为非白色则停止。
  2. 对所有4个方面都这样做。
  3. 这样,我学会了每边白边的宽度,并可以相应地修剪它。

    我想,上面的方法相当慢。有没有更有效的方法来实现这一目标?即,iOS是否提供任何有助于完成此任务的功能?

2 个答案:

答案 0 :(得分:1)

它可能不是最佳解决方案,但正如您所说,您可以检查颜色,然后修剪。这是一种获取图像中像素颜色的方法:

- (UIColor)colorOfPixelAtLocation:(CGPoint)position inImage:(UIImage *)image
{
    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((image.size.width  * position.y) + position.x ) * 4; // PNG

    UInt8 red = data[pixelInfo];
    UInt8 green = data[(pixelInfo + 1)];
    UInt8 blue = data[pixelInfo + 2];

    CFRelease(pixelData);

    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f]; 
}

修剪的代码:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);

// Use the image

CGImageRelease(imageRef);

我希望它有所帮助。

答案 1 :(得分:-1)

我会欺骗。假设您的图像周围有一个10px的白色边框,图像为200x 200,将其显示在尺寸为180x180的UIImageView中,并使其无中心缩放:P