在c#中处理图像对象时,最佳做法是什么?

时间:2012-02-24 05:34:57

标签: c#

我有两段代码。第一段没有明确处理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;
    }

虔诚地追随哪一个。请建议

1 个答案:

答案 0 :(得分:2)

您应该始终将一次性实例丢弃。所以采取后者。

你可以让它更具可读性:

       using (MemoryStream stream = new MemoryStream(ImageBytes))
       using(var newImage = System.Drawing.Image.FromStream(stream))
       {
         // ...

注意:在using语句之外声明变量是没有意义的。你不应该在外面使用它。