是否可以在 C# 中调整图像大小并将输出直接发送到浏览器,因为与 FF 或 chrome 相比,通过 IE 调整大小很糟
本文关键字:调整 浏览器 因为 FF chrome IE 通过 相比 接发 图像 是否 | 更新日期: 2023-09-27 18:30:49
我正在使用像 600x400 像素这样的大图像。 对于网页
当我缩小尺寸(160x127像素)时,这些图像在FF,Chrome,Safari上看起来不错,但在IE 9及以下版本上看起来很糟糕。
我能否以某种方式读取 Web 服务器上的物理文件并将其调整为更小的维度并将该二进制文件发送到客户端浏览器。
我不确定这种方法是否会解决IE的问题。
我将不胜感激代码示例或开始指针。
jQuery是否有任何算法可以在不损失质量的情况下重新调整图像大小
我找到了这个来源
One way to "normalize" the appearance in the different browsers is using your "server-side" to resize the image. An example using a C# controller:
public ActionResult ResizeImage(string imageUrl, int width)
{
WebImage wImage = new WebImage(imageUrl);
wImage = WebImageExtension.Resize(wImage, width);
return File(wImage.GetBytes(), "image/png");
}
where WebImage is a class in System.Web.Helpers.
WebImageExtension is defined below:
using System.IO;
using System.Web.Helpers;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
public static class WebImageExtension
{
private static readonly IDictionary<string, ImageFormat> TransparencyFormats =
new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };
public static WebImage Resize(this WebImage image, int width)
{
double aspectRatio = (double)image.Width / image.Height;
var height = Convert.ToInt32(width / aspectRatio);
ImageFormat format;
if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
{
return image.Resize(width, height);
}
using (Image resizedImage = new Bitmap(width, height))
{
using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
{
using (Graphics g = Graphics.FromImage(resizedImage))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, width, height);
}
}
using (var ms = new MemoryStream())
{
resizedImage.Save(ms, format);
return new WebImage(ms.ToArray());
}
}
}
}
note the option InterpolationMode.HighQualityBicubic. This is the method used by Chrome.
Now you need publish in a web page. Lets going use razor:
<img src="@Url.Action("ResizeImage", "Controller", new { urlImage = "<url_image>", width = 35 })" />
And this worked very fine to me!
Ideally will be better to save the image beforehand in diferent widths, using this resize algorithm, to avoid the controller process in every image load.
(Sorry for my poor english, I'm brazilian...)
我将尝试此代码,看看是否可以解决我的图像问题。
在服务器端,这可以通过System.Drawing.Image轻松完成:
var origImg = Image.FromStream(imgSrcStream);
var resizedBitmap = new Bitmap(origImg, newWidth, newHeight);
resizedBitmap.Save( resizedImageStream, ImageFormat.Png );
要保留比例,请使用 origImg.Width 和 origImg.Height 来计算所需的 newWidth 和 newHeight。