如何使用asp.net C#重新调整图像大小而不保存它

时间:2014-10-11 18:25:12

标签: c# asp.net image

我使用此代码重新调整图像大小,但我的问题是我必须保存原始图片然后重新调整大小!如何在不保存的情况下重新调整图片大小? 我想先重新调整图片大小,然后保存。

 FileUpload1.SaveAs("saveOriginalFileFirstHere");
 string thumbpath = "where resized pic should be saved";
 MakeThumbnails.makethumb("saveOriginalFileFirstpath", thumbpath);


 public static void makethumb(string savedpath, string thumbpath)

 {
   int resizeToWidth = 200;
   int resizeToHeight = 200;
   Graphics graphic;
   //Image photo; // your uploaded image
   Image photo = new Bitmap(savedpath);
   //  Image photo = new  j
   Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);
   graphic = Graphics.FromImage(bmp);
   graphic.InterpolationMode = InterpolationMode.Default;
   graphic.SmoothingMode = SmoothingMode.Default;
   graphic.PixelOffsetMode = PixelOffsetMode.Default;
   graphic.CompositingQuality = CompositingQuality.Default;
   graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
   bmp.Save(thumbpath);
 }

1 个答案:

答案 0 :(得分:0)

使用上传文件的InputStream属性:

我已经修改了你的代码:

编辑:你真的应该处理你的IDisposables,比如你的位图和流,以避免内存泄漏。我已更新了我的代码,因此在完成这些资源后,它会妥善处理这些资源。

 string thumbpath = "where resized pic should be saved";
 MakeThumbnails.makethumb(FileUpload1.InputStream, thumbpath);


 public static void makethumb(Stream stream, string thumbpath)
 {
    int resizeToWidth = 200;
    int resizeToHeight = 200;

    using (stream)
    using (Image photo = new Bitmap(stream))
    using (Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight))
    using (Graphics graphic = Graphics.FromImage(bmp))
    {
        graphic.InterpolationMode = InterpolationMode.Default;
        graphic.SmoothingMode = SmoothingMode.Default;
        graphic.PixelOffsetMode = PixelOffsetMode.Default;
        graphic.CompositingQuality = CompositingQuality.Default;
        graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
        bmp.Save(thumbpath);
    }
 }

这应该按照你想要的方式工作,如果它没有,或者如果有什么不清楚,请告诉我。