您的位置:首页 > 其它

高质量图片压缩低失真

2017-04-18 21:01 239 查看
private byte[] ZipImageSize(byte[] bytes, int width, int height, string formattype)
{
Stream bs = new MemoryStream(bytes);
//从文件取得图片对象
System.Drawing.Image myImage = System.Drawing.Image.FromStream(bs, true);
int ow = myImage.Width;
int oh = myImage.Height;
//缩略图宽、高
double newWidth = myImage.Width, newHeight = myImage.Height;
//宽大于模版的横图
if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
{
if (myImage.Width > width)
{
//宽按模版,高按比例缩放
newWidth = width;
newHeight = myImage.Height * (newWidth / myImage.Width);
}
}
//高大于模版的竖图
else
{
if (myImage.Height > height)
{
//高按模版,宽按比例缩放
newHeight = height;
newWidth = myImage.Width * (newHeight / myImage.Height);
}
}

//图片压缩
Image imgThumb = new Bitmap((int)newWidth, (int)newHeight);
Graphics g = Graphics.FromImage(imgThumb);
var destRect = new Rectangle(0, 0, (int) newWidth, (int) newHeight);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(myImage, destRect, 0, 0, ow, oh, GraphicsUnit.Pixel);
myImage.Dispose();

Stream ms = new MemoryStream();
if (formattype == "JPEG")
{
imgThumb.Save(ms, ImageFormat.Jpeg);
}
else if (formattype == "PNG")
{
imgThumb.Save(ms, ImageFormat.Png);
}
else if (formattype == "BMP")
{
imgThumb.Save(ms, ImageFormat.Bmp);
}
else if (formattype == "GIF")
{
imgThumb.Save(ms, ImageFormat.Gif);
}
else if (formattype == "ICON")
{
imgThumb.Save(ms, ImageFormat.Icon);
}

else if (formattype == "JPG")
{
imgThumb.Save(ms, ImageFormat.Jpeg);
}

byte[] buffer = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: