在 Monotouch 中调整图像大小并将其保存到磁盘 [英] Resize and saving an image to disk in Monotouch

查看:32
本文介绍了在 Monotouch 中调整图像大小并将其保存到磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to resize an image loaded from disk - a JPG or PNG (I don't know the format when I load it) - and then save it back to disk.

我有下面的代码,我试图从objective-c 移植,但是我在最后一部分被卡住了.原始Objective-C.

I've got the following code which I've tried to port from objective-c, however I've got stuck on the last parts. Original Objective-C.

这可能不是实现我想做的事情的最佳方式 - 任何解决方案都适合我.

This may not be the best way of achieving what I want to do - any solution is fine for me.

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);
    */
}

推荐答案

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

In the upcoming MonoTouch we will have a scale method, this is its implementation in 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;         
    }

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

Adjusted to be reused outside of 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;         
    }

这篇关于在 Monotouch 中调整图像大小并将其保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆