项目的登陆界面如果始终都是一张图,时间看久了,都会厌倦,有没有什么方法能让系统自己每天换图,又不用维护人员自己维护图片的方法?
微软bing上的图片每天都在更新,我只需要每天用它上传上去的图片当作背景,就可以做到每天登录背景不重样了。
效果是这样的
首先我们写个方法,将本地图片和Bing上的图片比对,不存在则下载
public static Image GetImageFromBing()
{
Image image = null;
String imagePath = Application.UserAppDataPath + "\\PICS";
if (!Directory.Exists(imagePath))
{
Directory.CreateDirectory(imagePath);
}
string fileName = imagePath + "\\" + DateTime.Today.ToString("yyyyMMdd") + ".JPG";
string oldFileName = imagePath + "\\" + DateTime.Today.AddDays(-7).ToString("yyyyMMdd") + ".JPG";
try
{
if (File.Exists(oldFileName))
{
File.Delete(oldFileName);
}
}
catch { }
if (!File.Exists(fileName))
{
try
{
string url = "https://www.bing.com/HPImageArchive.aspx?idx=0&n=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8";
string XmlString;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream myResponseStream = response.GetResponseStream();
using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))
{
XmlString = myStreamReader.ReadToEnd();
}
}
// 定义正则表达式用来匹配标签
Regex regImg = new Regex("<Url>(?<imgUrl>.*?)</Url>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(XmlString);
// 取得匹配项列表
string ImageUrl = "http://www.bing.com" + matches[0].Groups["imgUrl"].Value;
image = downloadImage(ImageUrl, fileName);
return image;
}
catch { return null; }
}
else
{
image = Image.FromFile(fileName);
return image;
}
}
然后更改尺寸
public static System.Drawing.Bitmap KiCut(System.Drawing.Image b)
{
int iHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
int iWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
int StartX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.X;
int StartY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Y;
if (b == null)
{
return null;
}
int w = b.Width;
int h = b.Height;
if (StartX >= w || StartY >= h)
{
return null;
}
if (StartX + iWidth > w)
{
iWidth = w - StartX;
}
if (StartY + iHeight > h)
{
iHeight = h - StartY;
}
try
{
System.Drawing.Bitmap bmpOut = new System.Drawing.Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
最后更改登录背景,没又联网则取当前桌面背景
try
{
Image image = DeskTop.GetImageFromBing();
if (image == null)
image = DeskTop.GetImage();
this.BackgroundImage = image;
this.BackgroundImageLayout = ImageLayout.Stretch;
}
catch
{
//CustomBackgroundImage =
this.BackgroundImage = DeskTop.GetImage();
}