MVC 生成图片,下载文件

时间:2023-03-10 01:52:11
MVC 生成图片,下载文件

/// <summary>
/// 生成图片
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public FileStreamResult GenerateImage(FormCollection collection)
{
var shopID = ShopCaches.GetShopInfo();
var headImgInfo = GetResourcePath(shopID.ShopID, collection["DaYinPersonnelID"], "HeadFront");
var imageInfo = GetResourcePath(shopID.ShopID, collection["inputGongHao"], "PersonNoBarcode");//转成图片类型
var filePath = Server.MapPath(string.Format("~/UI/Images/WorkCardPicture/{0}", shopID.ShopID));
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
const int WIDTH = 350, HEIGHT = 230;
var font12B = new Font(FontFamily.GenericSerif, 12.0f, FontStyle.Regular);
var font20B = new Font(FontFamily.GenericSerif, 15.0f, FontStyle.Bold);

using (var bitmap = new Bitmap(WIDTH, HEIGHT))
{
using (Graphics garphics = Graphics.FromImage(bitmap))
{
garphics.Clear(Color.White);
garphics.DrawString(shopID.ShopName, font20B, Brushes.Black, 126, 10);
if (headImgInfo!=null)
{
garphics.DrawImage(headImgInfo,28,57,80,100); //照片
}
garphics.DrawString("工号:" + collection["inputGongHao"], font12B, Brushes.Black, 197, 53);
garphics.DrawString("姓名:" + collection["inputXingMing"], font12B, Brushes.Black, 197, 78);
garphics.DrawString("职位:" + collection["inputZhiWei"], font12B, Brushes.Black, 197, 103);
garphics.DrawImage(imageInfo, new Point(197, 151)); //条码

bitmap.Save(filePath + "/" + collection["inputGongHao"] + ".jpg");
}
}
var path = filePath + "\\" + collection["inputGongHao"] + ".jpg";
return File(new FileStream(path, FileMode.Open), "image/jpeg",Server.UrlEncode(collection["inputGongHao"]+".jpg"));
//return Json("");
}

/// <summary>
/// 生成图片:获取相应图片的路径(先取本地;本地没有取资源服务器)
/// </summary>
/// <param name="shopID">店铺ID</param>
/// <param name="fileName">要取的图片的名字</param>
/// <param name="folderName">文件夹的名字</param>
/// <returns>图片路径</returns>
private Image GetResourcePath(Guid shopID, string fileName, string folderName)
{
Image headImgInfo = null;
const string URL = "~/UI/Images";
string httpurl = WebConfig.ResourceServerInformation;
//判断本地是否有
var path = Server.MapPath(string.Format("{0}/{1}/{2}/{3}", URL, folderName, shopID, fileName + ".jpg"));
var httpPath =string.Format("{0}/{1}/{2}/{3}", httpurl, folderName, shopID, fileName + ".jpg");
if (System.IO.File.Exists(path))
{
headImgInfo = Image.FromFile(path);
}
else if (httpPath!="")
{
//本地没有,先把图片下载下来在转换
string diZhi = Server.MapPath(string.Format("{0}/{1}/{2}/{3}", URL, folderName, shopID,fileName+".jpg"));
var webClient = new WebClient();
try
{
webClient.DownloadFile(httpPath, diZhi);//将资源服务器的图片下载到本地(这里会有异常)
headImgInfo = Image.FromFile(diZhi);
}
catch{
headImgInfo = null;
}
}
return headImgInfo;
}