/// <summary>
/// 生成带二维码的专属推广图片
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public string Draw(WxUser user)
{
//背景图片
string path = Server.MapPath("/Content/images/tg.jpg");
System.Drawing.Image imgSrc = System.Drawing.Image.FromFile(path);
//处理二维码图片大小 240*240px
System.Drawing.Image qrCodeImage = ReduceImage("https://www.easck.com/cgi-bin/showqrcode?ticket="+user.ticket, 240, 240);
//处理头像图片大小 100*100px
Image titleImage = ReduceImage(user.headimgurl, 100, 100);
using (Graphics g = Graphics.FromImage(imgSrc))
{
//画专属推广二维码
g.DrawImage(qrCodeImage, new Rectangle(imgSrc.Width - qrCodeImage.Width - 200,
imgSrc.Height - qrCodeImage.Height - 200,
qrCodeImage.Width,
qrCodeImage.Height),
0, 0, qrCodeImage.Width, qrCodeImage.Height, GraphicsUnit.Pixel);
//画头像
g.DrawImage(titleImage, 8, 8, titleImage.Width, titleImage.Height);
Font font = new Font("宋体", 30, FontStyle.Bold);
g.DrawString(user.nickname, font, new SolidBrush(Color.Red), 110, 10);
}
string newpath = Server.MapPath(@"/Content/images/newtg_" + Guid.NewGuid().ToString() + ".jpg");
imgSrc.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
return newpath;
}
/// <summary>
/// 缩小/放大图片
/// </summary>
/// <param name="url">图片网络地址</param>
/// <param name="toWidth">缩小/放大宽度</param>
/// <param name="toHeight">缩小/放大高度</param>
/// <returns></returns>
public Image ReduceImage(string url, int toWidth, int toHeight)
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
Image originalImage = Image.FromStream(responseStream);
if (toWidth <= 0 && toHeight <= 0)
{
return originalImage;
}
else if (toWidth > 0 && toHeight > 0)
{
if (originalImage.Width < toWidth && originalImage.Height < toHeight)
return originalImage;
}
else if (toWidth <= 0 && toHeight > 0)
{
if (originalImage.Height < toHeight)
return originalImage;
toWidth = originalImage.Width * toHeight / originalImage.Height;
}
else if (toHeight <= 0 && toWidth > 0)
{
if (originalImage.Width < toWidth)
return originalImage;
toHeight = originalImage.Height * toWidth / originalImage.Width;
}
Image toBitmap = new Bitmap(toWidth, toHeight);
using (Graphics g = Graphics.FromImage(toBitmap))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(originalImage,
new Rectangle(0, 0, toWidth, toHeight),
new Rectangle(0, 0, originalImage.Width, originalImage.Height),
GraphicsUnit.Pixel);
originalImage.Dispose();
return toBitmap;
}
}