我正在尝试将图像从手机上传到我的网络服务,并注意到上传图像时图像方向丢失。在上传之前我需要做些什么来确保图像以正确的方向上传吗?
我还查看了其他地方,找到了用于旋转图像的 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;
}