在Monotouch中调整图像大小并将其保存到磁盘

Chr*_*s S 7 resize objective-c uiimage xamarin.ios

我正在尝试调整从磁盘加载的图像的大小 - JPG或PNG(我加载它时不知道格式) - 然后将其保存回磁盘.

我有以下代码,我试图从objective-c移植,但是我已经卡在最后的部分.原始目标-C.

这可能不是实现我想做的最佳方式 - 任何解决方案对我来说都没问题.

int width = 100;
int height = 100;

using (UIImage image = UIImage.FromFile(filePath))
{
    CGImage cgimage = image.CGImage;
    CGImageAlphaInfo alphaInfo = cgimage.AlphaInfo;

    if (alphaInfo == CGImageAlphaInfo.None)
        alphaInfo = CGImageAlphaInfo.NoneSkipLast;

    CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
        width,
        height,
        cgimage.BitsPerComponent,
        4 * width,
        cgimage.ColorSpace,
        alphaInfo);

    context.DrawImage(new RectangleF(0, 0, width, height), cgimage);

    /*
    Not sure how to convert this part:

    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);
    */
}
Run Code Online (Sandbox Code Playgroud)

mig*_*aza 20

在即将推出的MonoTouch中,我们将有一个scale方法,这是它在UIImage.cs中的实现:

    public UIImage Scale (SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }
Run Code Online (Sandbox Code Playgroud)

调整为在MonoTouch之外重复使用:

    public static UIImage Scale (UIImage source, SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), source.CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }
Run Code Online (Sandbox Code Playgroud)