问题描述
我正在尝试从中心裁剪我的 JPEG(纵向和横向)以在产品列表上以 1:1 的比例显示。
这是我目前尝试过的:
视图模型:
public class Homeviewmodel
{
public List<HomeProductList> ProductList { get; internal set; }
}
public class HomeProductList
{
public int Id { get; set; }
public Image Thumbnail { get; set; }
public string Photo { get; set; } // Ex: 2021031122101047389.jpg
}
Linq 查询:
var culture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant();
var ImagePath = "/img/";
var products = (from p in _context.Products
join pd in _context.ProductDescribeFulls on p.Id equals pd.ProductId
select new HomeProductList
{
Id = p.Id,Photo = ImagePath + pd.Photo
});
foreach (HomeProductList prod in products)
{
if (prod.Photo != null)
{
prod.Thumbnail = ResizeImage(Image.FromFile(prod.Photo),new Size(45,45));
}
}
ResizeImage 方法:
public static Image ResizeImage(Image imgToResize,Size destinationSize)
{
var originalWidth = imgToResize.Width;
var originalHeight = imgToResize.Height;
//how many units are there to make the original length
var hRatio = (float)originalHeight / destinationSize.Height;
var wRatio = (float)originalWidth / destinationSize.Width;
//get the shorter side
var ratio = Math.Min(hRatio,wRatio);
var hScale = Convert.ToInt32(destinationSize.Height * ratio);
var wScale = Convert.ToInt32(destinationSize.Width * ratio);
//start cropping from the center
var startX = (originalWidth - wScale) / 2;
var startY = (originalHeight - hScale) / 2;
//crop the image from the specified location and size
var sourceRectangle = new Rectangle(startX,startY,wScale,hScale);
//the future size of the image
var bitmap = new Bitmap(destinationSize.Width,destinationSize.Height);
//fill-in the whole bitmap
var destinationRectangle = new Rectangle(0,bitmap.Width,bitmap.Height);
//generate the new image
using (var g = Graphics.FromImage(bitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize,destinationRectangle,sourceRectangle,GraphicsUnit.Pixel);
}
return bitmap;
}
这里出现了这个错误:
“/”应用程序中的服务器错误。 /img/2021031122101047389.jpg 说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误及其在代码中的来源的更多信息。
异常详情:System.IO.FileNotFoundException:/img/2021031122101047389.jpg prod.Thumbnail = ResizeImage(Image.FromFile("/img/2021031122101047389.jpg"),45));
但是:http://localhost:903/img/2021031122101047389.jpg 显示我的图片!
...
Id = p.Id,Thumbnail = ResizeImage(Image.FromFile(ImagePath + pd.Photo),45)),Photo = ImagePath + pd.Photo
...
我收到此错误:
LINQ to Entities 无法识别方法 'System.Drawing.Image ResizeImage(System.Drawing.Image,System.Drawing.Size)' 方法,并且此方法无法转换为存储表达式。 说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误及其在代码中的来源的更多信息。
异常详细信息:System.NotSupportedException:LINQ to Entities 无法识别方法 'System.Drawing.Image ResizeImage(System.Drawing.Image,System.Drawing.Size)' 方法,并且此方法无法转换为存储表达。
有什么好主意吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)