我正在尝试将手机中的图像上传到我的网络服务,但我注意到在上传图像时图像方向丢失了。在上传之前我需要做些什么来确保图像以正确的方向上传吗?
我也在别处找到了用于旋转图像的 Objective-C 代码,我将其转换为 C#,但每次使用旋转方法时,图像都会变黑,即我猜没有任何显示。
我附上我的代码供您引用,如果有人能告诉我我做错了什么,我将非常非常感激。谢谢!
public static UIImage RotateImage(this UIImage image)
{
UIImage imageToReturn = null;
if(image.Orientation == UIImageOrientation.Up)
{
imageToReturn = image;
}
else
{
CGAffineTransform transform = CGAffineTransform.MakeIdentity();
switch (image.Orientation) {
case UIImageOrientation.Down:
case UIImageOrientation.DownMirrored:
transform.Translate(image.Size.Width, image.Size.Height);
transform.Rotate((float)Math.PI);
break;
case UIImageOrientation.Left:
case UIImageOrientation.LeftMirrored:
transform.Translate(image.Size.Width, 0);
transform.Rotate((float)Math.PI/2);
break;
case UIImageOrientation.Right:
case UIImageOrientation.RightMirrored:
transform.Translate(0, image.Size.Height);
transform.Rotate((float)-Math.PI/2);
break;
case UIImageOrientation.Up:
case UIImageOrientation.UpMirrored:
break;
}
switch (image.Orientation) {
case UIImageOrientation.UpMirrored:
case UIImageOrientation.DownMirrored:
transform.Translate(image.Size.Width, 0);
transform.Scale(-1, 1);
break;
case UIImageOrientation.LeftMirrored:
case UIImageOrientation.RightMirrored:
transform.Translate(image.Size.Height, 0);
transform.Scale(-1, 1);
break;
case UIImageOrientation.Up:
case UIImageOrientation.Down:
case UIImageOrientation.Left:
case UIImageOrientation.Right:
break;
}
//now draw image
using(var context = new CGBitmapContext(IntPtr.Zero,
(int)image.Size.Width,
(int)image.Size.Height,
image.CGImage.BitsPerComponent,
image.CGImage.BytesPerRow,
image.CGImage.ColorSpace,
image.CGImage.BitmapInfo)){
context.ConcatCTM(transform);
switch (image.Orientation)
{
case UIImageOrientation.Left:
case UIImageOrientation.LeftMirrored:
case UIImageOrientation.Right:
case UIImageOrientation.RightMirrored:
// Grr...
context.DrawImage(new RectangleF(PointF.Empty,new SizeF(image.Size.Height, image.Size.Width)), image.CGImage);
break;
default:
context.DrawImage(new RectangleF(PointF.Empty, new SizeF(image.Size.Width, image.Size.Height)), image.CGImage);
break;
}
using(var imageRef = context.ToImage())
{
imageToReturn = new UIImage(imageRef);
}
}
}
return imageToReturn;
}
最佳答案
你得到黑色图像的原因是平移和旋转调用是向后的。 iPod/iphone 上的普通人像图片处于“正确”方向。转换它们的正确代码使用:
case UIImageOrientation.Right:
case UIImageOrientation.RightMirrored:
transform.Rotate (-(float)Math.PI / 2);
transform.Translate (0, input.Size.Height);
break;
转换函数依赖于顺序。此代码将其旋转到正确的方向,但由于旋转大约是左下角的 0,0 坐标,因此图像现在刚好位于框架的底部。然后翻译将它推到它所属的位置。
原始代码会将侧面图像推离框架的顶部,然后旋转会使图像向右旋转,但会远离框架的右侧。
使用较小的高度值,如 100 或 200 和 pi/4 将很容易显示更改这些函数的顺序时获得的差异,因为某些原始图像始终可见。
关于ios - 旋转 UIImage Monotouch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452358/