我正在尝试旋转保留所有像素的位图,并设置目标位图大小,以便我以相同的比例获得它。换句话说,源中的每个像素都是输出中的不同像素,并且输出位图大小会调整以匹配。
我已经尝试了很多东西(下面的代码在一个带有位图文件的 zip 中)。但我得到的是输出中的部分图像,在某些情况下,按比例缩小。
注意:这里列出了很多解决方案,但它们都存在这段代码演示的相同问题。
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace RotateBitmap
{
class Program
{
static void Main(string[] args)
{
RotateBitmap("cows.png", "cows_rotated.png", 90);
RotateBitmap("zoey.jpeg", "zoey_rotated.png", 45);
}
static void RotateBitmap(string srcFilename, string destFilename, double degrees)
{
srcFilename = Path.GetFullPath(Path.Combine("../..", srcFilename));
destFilename = Path.GetFullPath(Path.Combine("../..", destFilename));
byte[] data = File.ReadAllBytes(srcFilename);
MemoryStream stream = new MemoryStream(data);
Bitmap srcBitmap = new Bitmap(stream);
double radians = Math.PI * degrees / 180;
double sin = Math.Abs(Math.Sin(radians)), cos = Math.Abs(Math.Cos(radians));
int srcWidth = srcBitmap.Width;
int srcHeight = srcBitmap.Height;
int rotatedWidth = (int)Math.Floor(srcWidth * cos + srcHeight * sin);
int rotatedHeight = (int)Math.Floor(srcHeight * cos + srcWidth * sin);
Bitmap rotatedImage = new Bitmap(rotatedWidth, rotatedHeight);
Graphics g = Graphics.FromImage(rotatedImage);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
// Set the rotation point to the center in the matrix
g.TranslateTransform(rotatedWidth / 2, rotatedHeight / 2);
// Rotate
g.RotateTransform((float)degrees);
// Restore rotation point in the matrix
g.TranslateTransform(-srcWidth / 2, -rotatedHeight / 2);
// Draw the image on the bitmap
g.DrawImage(srcBitmap, 0, 0);
srcBitmap.Dispose();
g.Dispose();
stream.Close();
stream = new MemoryStream();
rotatedImage.Save(stream, ImageFormat.Png);
data = stream.ToArray();
File.WriteAllBytes(destFilename, data);
}
}
}