我有两段代码。第一段没有明确处理Image对象,而第二块正确处理它。请建议在生产代码中使用哪一个。
private bool SavePatientChartImage(byte[] ImageBytes, string ImageFilePath, string IMAGE_NAME, int rotationAngle)
{
bool success = false;
System.Drawing.Image newImage;
try
{
using (MemoryStream stream = new MemoryStream(ImageBytes))
{
newImage = System.Drawing.Image.FromStream(stream);
switch (rotationAngle)
{
case 90:
newImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 180:
newImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 270:
newImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
default:
newImage = newImage;
break;
}
newImage.Save(Path.Combine(ImageFilePath, IMAGE_NAME));
success = true;
}
}
catch (Exception ex)
{
success = false;
}
return success;
}
和
private bool SavePatientChartImage(byte[] ImageBytes, string ImageFilePath, string IMAGE_NAME, int rotationAngle)
{
bool success = false;
System.Drawing.Image newImage;
try
{
using (MemoryStream stream = new MemoryStream(ImageBytes))
{
using(newImage = System.Drawing.Image.FromStream(stream))
{
switch (rotationAngle)
{
case 90:
newImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 180:
newImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 270:
newImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
default:
newImage = newImage;
break;
}
newImage.Save(Path.Combine(ImageFilePath, IMAGE_NAME));
success = true;
}
}
}
catch (Exception ex)
{
success = false;
}
return success;
}
虔诚地追随哪一个。请建议
答案 0 :(得分:2)
您应该始终将一次性实例丢弃。所以采取后者。
你可以让它更具可读性:
using (MemoryStream stream = new MemoryStream(ImageBytes))
using(var newImage = System.Drawing.Image.FromStream(stream))
{
// ...
注意:在using语句之外声明变量是没有意义的。你不应该在外面使用它。