【发布时间】:2020-04-10 22:45:45
【问题描述】:
我正在尝试旋转保留所有像素的位图,并设置目标位图大小,以便我以相同的比例获得它。换句话说,源中的每个像素都是输出中的一个不同像素,并且输出位图大小会调整以匹配。
我尝试了很多东西 (below code here in a zip with bitmap files)。但我得到的是输出中的部分图像,在某些情况下,缩小了。
注意:这里列出了很多解决方案,但它们都有这段代码演示的相同问题。
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);
}
}
}
【问题讨论】:
-
“换句话说,源中的每个像素都是输出中的不同像素” - 除非您旋转 90 度的精确倍数,否则这根本行不通。
-
顺便说一句,你也应该在保存
rotatedImage后处理它。
标签: bitmap system.drawing image-rotation system.drawing.graphics