我正在尝试调整从磁盘加载的图像的大小 - JPG 或 PNG(加载时我不知道格式)- 然后将其保存回磁盘。
我有以下代码,我试图从 objective-c 移植这些代码,但是我卡在了最后一部分。 Original Objective-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);
*/
}
最佳答案
在即将到来的 MonoTouch 中我们将有一个缩放方法,这是它在 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 之外重复使用:
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;
}
关于objective-c - 在 Monotouch 中调整大小并将图像保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2417969/