最近有点忙,没时间写文章,写一篇短点的东西:tinypng.com的API DEMO(图片压缩接口,如果希望更快速地处理任务,可以在实际使用中进行多线程优化)。
*tinypng.com是一个图片压缩网站,每个账号可以享受500张/月的免费API配额,网页版没有次数限制。
public class ApiResponse
{
public Input input { get; set; }
public Output output { get; set; }
}
public class Input
{
public int size { get; set; }
public string type { get; set; }
}
public class Output
{
public int size { get; set; }
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public float ratio { get; set; }
public string url { get; set; }
}
class Program
{
const string output = @"C:\output";
static void Main(string[] args)
{
string key =
Convert.ToBase64String(Encoding.ASCII.GetBytes("api:" + Console.ReadLine()));
string[] files = Directory.GetFiles("photoes");
for (int i = 0; i < files.Length; i++)
{
FileInfo finfo = new FileInfo(files[i]);
WebClient client = new WebClient();
client.Headers["Authorization"] = "Basic " + key;
var res = Encoding.ASCII.GetString(client.UploadData("https://api.tinify.com/shrink", File.ReadAllBytes(files[i])));
try
{
ApiResponse obj = JsonConvert.DeserializeObject<ApiResponse>(res);
Console.WriteLine($"{i + 1} of {files.Length}\t{finfo.Name}\t{finfo.Length / 1000} -> {obj.output.size / 1000}");
client.DownloadFile(obj.output.url, Path.Combine(output, finfo.Name));
}
catch (Exception ex)
{
Console.WriteLine("error\r\n" + res + "\r\n" + ex.ToString());
Console.ReadLine();
}
}
Console.ReadLine();
}
}