图片压缩到小于指定大小,注意是压缩,不是生成缩略片改变大小。
using System;
using System.Collections.Generic;
using System.Linq;
//using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Xunit;
namespace TestOnly
{
public class TestOnlyFixture
{
[Fact]
public void Compression()
{
string fileName = "bg.jpg";
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
Compression(filePath);
}
private void Compression(string filePath)
{
FileInfo file = new FileInfo(filePath);
decimal fileSize = Math.Round((decimal)file.Length / 1024, 1); // KB
if (fileSize > 60) // Optimazed image shouldn't be more than 60KB
{
Image originalImage = Image.FromFile(filePath);
Bitmap bitmap = new Bitmap(originalImage);
ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(it => it.MimeType == "image/jpeg");
EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, 30L);
encoderParameters.Param[0] = encoderParameter;
originalImage.Dispose();
bitmap.Save(filePath, imageCodecInfo, encoderParameters); // Override
// More than 60KB will compression again
Compression(filePath);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
//using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Xunit;
namespace TestOnly
{
public class TestOnlyFixture
{
[Fact]
public void Compression()
{
string fileName = "bg.jpg";
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
Compression(filePath);
}
private void Compression(string filePath)
{
FileInfo file = new FileInfo(filePath);
decimal fileSize = Math.Round((decimal)file.Length / 1024, 1); // KB
if (fileSize > 60) // Optimazed image shouldn't be more than 60KB
{
Image originalImage = Image.FromFile(filePath);
Bitmap bitmap = new Bitmap(originalImage);
ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(it => it.MimeType == "image/jpeg");
EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, 30L);
encoderParameters.Param[0] = encoderParameter;
originalImage.Dispose();
bitmap.Save(filePath, imageCodecInfo, encoderParameters); // Override
// More than 60KB will compression again
Compression(filePath);
}
}
}
}
我比较喜欢Xunit,写个项目放那里,需要测试点东西的时候,就开起来用下,很方便。