项目需要,经常需要手动压缩图片,流程太过麻烦,效率低下。所以写了一个小程序,以提高工作效率
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);
}
}
}
时间: 2024-10-15 21:30:52