渐进式Jpg图片

时间:2021-10-05 19:39:20

        网速比较慢的时候,会出现图片的空白,为了提升用户体验,可以先加载一个缩略图,然后加载一个渐进式图片(从模糊到清晰);实现中暂时只放出来图片byte[]的转换,其实可以实现stream,bitmap等的转换,不再列举;

       ps:需要借助Magick.NET

 

        /// <summary>
/// 转换Jpg渐进式
/// </summary>
/// <param name="data">图片数据</param>
/// <returns></returns>
public byte[] ConvertProgressive(byte[] data)
{
byte[] resData = null;
using (MemoryStream mStream = new MemoryStream())
{
using (MagickImage image = new MagickImage(data))
{
image.Format = MagickFormat.Pjpeg;
image.Write(mStream);
}
resData = mStream.ToArray();
}
return resData;
}

/// <summary>
/// 固定宽度等比缩放图片
/// </summary>
/// <param name="data"></param>
/// <param name="width"></param>
/// <returns></returns>
public byte[] ScaleImageByWith(byte[] data, int width)
{
byte[] resData = null;
using (MagickImage image = new MagickImage(data))
{
var imageSmall = image.Clone();
imageSmall.Scale(width, image.Height * width / image.Width);
using (MemoryStream mStream = new MemoryStream())
{
imageSmall.Write(mStream);
resData = ConvertProgressive(mStream.ToArray()) ;
}
}
return resData;
}