使用SkiaSharp旋转照片 [英] Rotate photo with SkiaSharp
问题描述
我正在尝试使用以下代码将 SkiaSharp
的照片旋转到90度:
I'm trying to rotate photo with SkiaSharp
to 90 degrees with following code:
public SKBitmap Rotate()
{
var bitmap = SKBitmap.Decode("test.jpg");
using (var surface = new SKCanvas(bitmap))
{
surface.RotateDegrees(90, bitmap.Width / 2, bitmap.Height / 2);
surface.DrawBitmap(bitmap.Copy(), 0, 0);
}
return bitmap;
}
但是当我将位图保存到 JPEG
文件时,它在图像的顶部和底部都有边距.
But when I save bitmap to JPEG
file, it has margins both on top and bottom of image.
原始图片: http://imgur.com/pGAuko8 .旋转图片: http://imgur.com/bYxpmI7 .
Original image: http://imgur.com/pGAuko8. Rotated image: http://imgur.com/bYxpmI7.
我在做什么错了?
推荐答案
您可能想要执行以下操作:
You may want to do something like this:
public static SKBitmap Rotate()
{
using (var bitmap = SKBitmap.Decode("test.jpg"))
{
var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
using (var surface = new SKCanvas(rotated))
{
surface.Translate(rotated.Width, 0);
surface.RotateDegrees(90);
surface.DrawBitmap(bitmap, 0, 0);
}
return rotated;
}
}
之所以这样做(或您的预期效果不佳),是因为您正在旋转位图本身.您基本上已经拍摄了一张图像,然后在将其绘制到第一张图像上时进行了复制.因此,您仍然可以从下图获得空白.
The reason for this (or yours not working as expected) is that you are rotating the bitmap on itself. You have basically taken an image, and then made a copy on draw it onto the first image. Thus, you still have the margins from the image below.
我要做的是创建一个新的位图,然后在其上绘制解码的位图.
What I did was to create a NEW bitmap and then draw the decoded bitmap onto that.
第二个问题"是您正在旋转图像,但没有更改画布尺寸.如果位图为50x100,然后旋转90度,则位图现在为100x50.由于创建位图后实际上无法更改其尺寸,因此必须创建一个新的位图.您可以在输出图像中看到它,因为它实际上已经被裁剪掉了.
The second "issue" is that you are rotating the image, but you are not changing the canvas dimensions. If the bitmap is 50x100, and then you rotate 90 degrees, the bitmap is now 100x50. As you can't actually change the dimensions of a bitmap once created, you have to create a new one. You can see this in the output image as it is actually cropped off a bit.
希望这会有所帮助.
这篇关于使用SkiaSharp旋转照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!