refer :
http://blog.csdn.net/qq_16542775/article/details/51792092
http://www.cnblogs.com/xinzhao/p/5130410.html
https://zhidao.baidu.com/question/495382546600556724.html
https://zh.m.wikipedia.org/zh/无损数据压缩
先说说常用的图片格式 :
jpeg, jpg
有损
大部分网页图片都是 jpg 格式的.
特点就是小
PNG (无损)
特点是支持透明
Gif (无损)
特点是支持动画
质量压缩 (有损要损和无损的区别)
有损指的是图片压缩后质量会流失, 压缩过程中会丢失图片信息 (由于人的肉眼有限, 所以部分信息即使丢失了,我们在网页也是看不出来的)
无损是通过去除冗余信息实现的,过程中不会丢失信息,类似 zip file 一样可以还原.
有损好处是可以压缩的很小.
尺寸压缩
尺寸指的是把 1000px * 1000px 的图片压缩成 100px * 100px
这样也可以让图片体积变少.
asp.net c# 代码 :
try { long quality = 90; //越高越清楚,越低size越小 int targetWidth = 800; int targetHeight = 0; string originalPath = @"C:keatkeatmy projectsThumbnailImageProjectProject est.jpg"; string newPath = @"C:keatkeatmy projectsThumbnailImageProjectProject est123.jpg"; using (Bitmap original = new Bitmap(originalPath)) { ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg"); Encoder encoder = Encoder.Quality; EncoderParameters encoderParameters = new EncoderParameters(1); EncoderParameter encoderParameter = new EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; int newWidth = 0; int newHeight = 0; if (targetWidth != 0) { decimal ratio = (decimal)targetWidth / original.Width; newWidth = targetWidth; newHeight = (int)(original.Height * ratio); } else { decimal ratio = (decimal)targetHeight / original.Height; newHeight = targetHeight; newWidth = (int)(original.Width * ratio); } using (Bitmap newImage = new Bitmap(newWidth, newHeight)) { newImage.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (Graphics g = Graphics.FromImage(newImage)) { g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(original, 0, 0, newWidth, newHeight); } newImage.Save(newPath, codecInfo, encoderParameters); } } } catch (Exception ex) { }
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
尺寸压缩原理就是重绘, js canvas 也可以完成. 质量压缩只能用于 jpg. js 也是可以做到的,只是兼容比较蛋疼.. /.
refer : https://github.com/think2011/localResizeIMG