C# 旋转图像-只读
我找到了旋转图像的代码。我的问题是,当我保存它时,图像已经打开,并且我正在使用它(因为,我打开它来旋转它) 我怎样才能避免这种情况C# 旋转图像-只读,c#,asp.net,C#,Asp.net,我找到了旋转图像的代码。我的问题是,当我保存它时,图像已经打开,并且我正在使用它(因为,我打开它来旋转它) 我怎样才能避免这种情况 public static void RotateImage(string filePath, float angle) { //create a new empty bitmap to hold rotated image using (var img = Image.FromFile(filePath))
public static void RotateImage(string filePath, float angle)
{
//create a new empty bitmap to hold rotated image
using (var img = Image.FromFile(filePath))
{
using(var bmp = new Bitmap(img.Width, img.Height))
{
//turn the Bitmap into a Graphics object
Graphics gfx = Graphics.FromImage(bmp);
//now we set the rotation point to the center of our image
gfx.TranslateTransform((float) bmp.Width/2, (float) bmp.Height/2);
//now rotate the image
gfx.RotateTransform(angle);
gfx.TranslateTransform(-(float) bmp.Width/2, -(float) bmp.Height/2);
//set the InterpolationMode to HighQualityBicubic so to ensure a high
//quality image once it is transformed to the specified size
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
//now draw our new image onto the graphics object
gfx.DrawImage(img, new Point(0, 0));
//dispose of our Graphics object
}
img.Save(filePath);
}
编辑:根据Anthony的建议更新代码
编辑:
仅供参考,这是在几行中完成的
public static void RotateImage(string filePath, float angle)
{
//create a new empty bitmap to hold rotated image
byte[] byt = System.IO.File.ReadAllBytes(filePath);
var ms = new System.IO.MemoryStream(byt);
using (Image img = Image.FromStream(ms))
{
RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
img.RotateFlip(r);
img.Save(filePath);
}
}
使用现有代码,可以执行以下操作:
byte[] byt = System.IO.File.ReadAllBytes(filepath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(byt);
Image img = Image.FromStream(ms);
这样在您保存文件时不会锁定该文件。是否可以保存为临时名称,然后在处理完所有内容后覆盖上一个文件?在这个主题上,您应该使用(var obj=new DisposableObject())将一次性对象包装成
,
谢谢Anthony-我希望有一种更干净的方法。。可能会以某种方式保存到内存流,然后处置img,然后将流保存到同一个文件?(谢谢-我已经使用并更新了问题)谢谢!没有锁的问题-但是,我的形象没有改变。一定在什么地方有虫子。