using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Drawing;
namespace ExplorerPlus.Utilities
{
public static class Web
{
///
/// Stores an image from the web to disk.
///
/// image url
/// directory path to store image to
/// the new path of the saved image path
public static string SaveImageToDisk(string url, string path)
{
if (System.IO.Directory.Exists(path))
{
string savedImagePath = System.IO.Path.Combine(path, System.IO.Path.GetFileName(url));
if (!File.Exists(savedImagePath))
{
System.Drawing.Image webImage = GetImage(url);
webImage.Save(savedImagePath);
}
return savedImagePath;
}
return string.Empty;
}
///
/// returns an image object from a web url stream.
///
/// image url
/// returns an image object from a web url stream.
public static System.Drawing.Image GetImage(string url)
{
Uri uri = CalculateUri(url);
if (uri.IsFile)
{
using (StreamReader reader = new StreamReader(uri.LocalPath))
{
return Image.FromStream(reader.BaseStream);
}
}
using (WebClient client = new WebClient())
{
using (Stream stream = client.OpenRead(uri))
{
return Image.FromStream(stream);
}
}
}
///
/// Tries to evaluate a url and return its valid location.
///
public static Uri CalculateUri(string path)
{
try
{
return new Uri(path);
}
catch (UriFormatException)
{
path = Path.GetFullPath(path);
return new Uri(path);
}
}
}
}