我尝试通过将上传的流保存到位图中来处理ASP.NET中上传图像的大小,处理此位图并将处理后的位图保存到应保存到FTP文件夹的新流中。上传的流成功保存为位图并正确处理;只是新处理的流出现问题,导致图像损坏。以下是代码段:
s = FileUpload1.FileContent;
Bitmap bitmap = (Bitmap)Bitmap.FromStream(s);
Bitmap newBmp = new Bitmap(250, 250, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newBmp.SetResolution(72F, 72F);
Graphics newGraphic = Graphics.FromImage(newBmp);
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(bitmap, 0, 0, 250, 250);
newBmp.Save(MapPath("temp.jpg"));
Stream memoryStream = new MemoryStream();
newBmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
答案 0 :(得分:4)
这里的关键是你得到一个空图像,这几乎总是一个从头开始不被读取的流。
在将位图写入后,您需要回到流的开头。
memoryStream.Seek(0, SeekOrigin.Begin); //go back to start
否则,当您稍后尝试保存该流时,它将从末尾读取流。当位图写入流时,它会附加字节,并使位置前进。以下是MVC中的示例代码。
<强> Index.cshtml 强>
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("UploadImage", "BitmapConvert", FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="file" name="uploadFile"/>
<input type="submit" value="Upload"/>
}
<强> BitmapConvertController.cs 强>
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace MvcSandbox.Controllers
{
public class BitmapConvertController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase uploadFile)
{
var s = uploadFile.InputStream;
var bitmap = new Bitmap(s);
var resizedBitmap = new Bitmap(250, 250, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
resizedBitmap.SetResolution(72F, 72F);
using (var g = Graphics.FromImage(resizedBitmap))
{
g.Clear(Color.White);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(bitmap, 0, 0, 250, 250);
resizedBitmap.Save("C:\\Test\\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
using (var memoryStream = new MemoryStream())
{
resizedBitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
using (var dest = new FileStream("C:\\Test\\stream.jpg", FileMode.OpenOrCreate))
{
memoryStream.Seek(0, SeekOrigin.Begin); //go back to start
memoryStream.CopyTo(dest);
}
}
}
return RedirectToAction("Index");
}
}
}