为了上传图片,我在客户端使用 plupload。然后在我的控制下我有下一个逻辑:
public ActionResult UploadFile()
{
try
{
var file = Request.Files.Count > 0 ? Request.Files[0] : null;
using (var fileStream = new MemoryStream())
{
using (var oldImage = new Bitmap(file.InputStream))
{
var format = oldImage.RawFormat;
using (var newImage = ImageUtility.ResizeImage(oldImage, 800, 2000))
{
newImage.Save(fileStream, format);
}
byte[] bits = fileStream.ToArray();
}
}
{
catch (Exception ex)
{
}
}
ImageUtility.ResizeImage 方法:
public static class ImageUtility
{
public static Bitmap ResizeImage(Bitmap image, int width, int height)
{
if (image.Width <= width && image.Height <= height)
{
return image;
}
int newWidth;
int newHeight;
if (image.Width > image.Height)
{
newWidth = width;
newHeight = (int)(image.Height * ((float)width / image.Width));
}
else
{
newHeight = height;
newWidth = (int)(image.Width * ((float)height / image.Height));
}
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphics.FillRectangle(Brushes.Transparent, 0, 0, newWidth, newHeight);
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
}
}
我在这里遇到的问题是图像大小增加了。 我上传了 1.62MB 的图像,在调用此 Controller 后,它会创建 Bitmap 实例,然后将 Bitmap 保存到文件流并使用“fileStream.ToArray();”读取位我得到 2.35MB 的“位”。
谁能告诉我在将图像保存为位图后增加图像大小的原因是什么?我需要位图,因为我需要检查上传图像的高度和高度,并在需要时调整它的大小。
最佳答案
答案很简单,无论图像之前采用何种格式,位图都会占用更多内存,因为它是未压缩的,保存后仍保持未压缩格式。
关于C#上传图片并另存为位图增加图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018791/