将位图保存到流中
本文关键字:保存 位图 | 更新日期: 2023-09-27 18:33:44
我正在尝试通过将上传的流保存到位图中,处理此位图并将处理后的位图保存到应保存到FTP文件夹的新流来调整上传 ASP.NET 图像的大小。上传的流已成功保存为位图并正确处理;只是新处理的流有问题,它呈现为损坏的图像。下面是一段代码:
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);
这里的关键是你得到一个空的图像,这几乎总是从一开始就没有被读取的流。
在将位图写入流后,需要查找回流的开头。
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"/>
}
位图转换控制器.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");
}
}
}