【发布时间】:2018-08-12 04:42:18
【问题描述】:
我正在寻找一种在 .NET 中有效地为网站准备大量图像的方法
图像通常是来自手机摄像头的大型、未经编辑、2-5MB 4000x8000 像素的怪物图像。
我想快速、尽可能高效地生成缩略图。 (不降低 CPU 速度)或用户性能。
我还得考虑缓存。
现代 CMS 系统正在使用您可以通过前端调用的图像预处理器。所以我也想做这样的东西,但是我自己的。因为就我而言,我不能在这里使用 CMS。
这是我的代码:我有一个来自 Helper 类的静态辅助方法。
每次我需要渲染图像时,我都会用剃刀调用它。
public static string GetImgThumbnail(string web_path, int _width = 0, int _height = 0)
{
//Default parameters
Image image;
Image thumbnail;
string thumb_url = "/img/noimg.png";
try
{
// web_path example input "/images/helloworld.jpg"
//system_path returns system path of Ogirinal image in the system f.e.: "C:\projects\websites\mysite\images\helloworld.jpg"
string system_path = HttpContext.Current.Server.MapPath(web_path);
image = Image.FromFile(system_path);
//Original image dimensions
int width = image.Width;
int height = image.Height;
//Get New image dimensions
if(_height == 0)
{
if(_width == 0)
{
_width = 700;
}
_height = (_width * height) / width;
}
if (_width == 0)
{
if (_height == 0)
{
_height = 700;
}
_width = (_height * width) / height;
}
//Generate Thumbnail, passing in new dimensions
thumbnail = image.GetThumbnailImage(_width, _height, null, IntPtr.Zero);
//Find out how to call newly created thumbnail.
//Original image example name = "/images/helloworld.jpg" thumbnail would be "/images/helloworld_thumb_700x250.jpg" or analogical with .png or JPEG etc...
//Suffix should be "_thumb_{width}x{height}"
string suffix = string.Format("_thumb_{0}x{1}", _width.ToString(),_height.ToString());
var bigImgFilename = String.Format("{0}{1}",
Path.GetFileNameWithoutExtension(system_path), Path.GetExtension(system_path));
var newImgFilename = String.Format("{0}{1}{2}",
Path.GetFileNameWithoutExtension(system_path), suffix, Path.GetExtension(system_path));
//New system path of new Thumbnail example: "C:\projects\websites\mysite\images\helloworld_thumb_700x250.jpg"
var newpath = system_path.Replace(bigImgFilename, newImgFilename);
//Set new web path, expect this to be: "/images/helloworld_thumb_700x250.jpg"
thumb_url = web_path.Replace(bigImgFilename, newImgFilename);
//Check if file exists, no need to overrite if file exists.
if (!File.Exists(newpath))
{
thumbnail.Save(newpath);
}
}
catch (Exception exc)
{
// If something goes wrong, just return backup image.
thumb_url = "/img/noimg.png";
}
// return thumbnail
return thumb_url;
}
想听听一些提示/建议,或者我是否走在正确的道路上,或者我应该以不同的方式去做?
【问题讨论】:
-
看看 ImageResizer 项目我不明白你的代码在计算宽度和高度时应该做什么,但第二组 ifs 不可能正确,因为它检查 _width 是否为 0 两次
-
谢谢,这是一个错字,我更正了我的代码示例。
-
离题但有一些实用的想法:您可以考虑像cloudimage.io 这样的云服务。一旦请求,他们将从您的位置下载图像,调整大小(可能的其他操作,如裁剪、应用过滤器、压缩)并返回缓存副本(从现在开始),一切只需更改 URL 即可。我知道,任何东西都可以编程,但这些服务有时会非常有用。
标签: c# asp.net-mvc image