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, 38, 57, 100, 110); //照片
}
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");
imageInfo.Dispose();//释放条形码的所有资源
garphics.Dispose();//释放资源
bitmap.Dispose();//释放资源
}
}
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;
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
{
var filePath = Server.MapPath(string.Format("{0}/{1}/{2}", URL, folderName, shopID));
//本地没有,先把图片下载下来在转换
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
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;
}

posted @ 2014-09-19 11:37  加油吧,小蜗牛  阅读(413)  评论(0编辑  收藏  举报