标签:ring exists files api read ini download tle try
using System;
using System.Net;
using System.Text;
using System.IO;
class Program
{
static void Main()
{
Console.WriteLine("请输入TinyPng.com的API KEY,获取地址:https://tinypng.com/developers");
string key = Console.ReadLine();
if (!System.IO.Directory.Exists("NewImg"))
{
System.IO.Directory.CreateDirectory("NewImg");
Console.WriteLine("已创建NewImg目录,请把需要处理的图片放到该目录下");
Console.ReadKey(true);
return;
}
if (!System.IO.Directory.Exists("CompressedImg")){
System.IO.Directory.CreateDirectory("CompressedImg");
}
string url = "https://api.tinify.com/shrink";
string[] fileStrs = System.IO.Directory.GetFiles("NewImg");
Console.WriteLine("共" + fileStrs.Length + "个文件,请等待下载完成...");
int num = 0;
foreach (string s in fileStrs)
{
System.IO.FileInfo info = new System.IO.FileInfo(s);
if (info.Extension == ".png" || info.Extension == ".jpg")
{
string input = @"NewImg/" + info.Name;
string output = @"CompressedImg/" + info.Name;
GetCompressImg(url, key, input, output);
num++;
}
}
Console.WriteLine("文件已下载到CompressedImg文件夹下,共" + num + "个文件");
Console.ReadKey(true);
}
static public void GetCompressImg(string url,string key,string input,string output){
WebClient client = new WebClient();
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes("api:" + key));
client.Headers.Add(HttpRequestHeader.Authorization, "Basic " + auth);
try
{
client.UploadData(url, File.ReadAllBytes(input));
client.DownloadFile(client.ResponseHeaders["Location"], output);
}
catch (WebException)
{
Console.WriteLine("网络请求失败:" + input);
}
}
}
标签:ring exists files api read ini download tle try
原文地址:http://www.cnblogs.com/xiejunzhao/p/c4e38db51d593f3f6e49bfb0e5421e25.html