在xamarin ios中裁剪图像

时间:2018-04-02 10:39:05

标签: xamarin xamarin.forms xamarin.ios

我正在获取图片,我想从中删除空白。所以我必须检查每个像素的颜色,如果完整的行是白色然后裁剪它。我无法得到任何解决方案,请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以尝试捕获图像的每个像素点的RGB。当其RGB等于白色时,将其alpha修改为0以将其删除。我为你指的是一个方法:

UIImage imageToTransparent(UIImage image)
{
    var imageWidth = (int)image.Size.Width;
    var imageHeight = (int)image.Size.Height;

    var bytesPerRow = imageWidth * 4;
    var rgbImageBuf = new byte[bytesPerRow * imageHeight];

    CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();

    CGContext context = new CGBitmapContext(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                        CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.NoneSkipLast);

    context.DrawImage(new CGRect(0, 0, imageWidth, imageHeight), image.CGImage);

    int pixelNum = imageWidth * imageHeight * 4;
    var pCurPtr = rgbImageBuf;

    for (int i = 0; i < pixelNum; i = i + 4)
    {
        // You can modify this scope to choose which color you want to remove
        if (pCurPtr[i + 1] > 240 && pCurPtr[i + 2] > 240 && pCurPtr[i + 3] > 240)
        {
            pCurPtr[i] = 0;
        }

    }

    CGDataProvider dataProvider = new CGDataProvider(rgbImageBuf);

    CGImage imageRef = new CGImage(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        CGBitmapFlags.Last | CGBitmapFlags.ByteOrder32Little, dataProvider,
                                        null, true, CGColorRenderingIntent.Default);

    dataProvider.Dispose();

    UIImage resultUIImage = new UIImage(imageRef);

    imageRef.Dispose();
    context.Dispose();
    colorSpace.Dispose();

    return resultUIImage;           
}