Wpf- Url到Bitmap Image快速

时间:2016-10-13 13:44:30

标签: c# wpf

在我的应用程序中,我调用一个函数GetThumbnail(),其中使用GetByteArrayFromRelPath()从URL下载为字节数组的图像,并由BitmapImage转换为ConvertToBitmapImage()。< / p>

但是当我在一次获得20-25张图像时,它需要大约13-15秒的时间,这将成为一个很长的时间。我需要快点做。这些是我正在使用的功能和属性。

public static byte[] GetByteArrayFromRelPath(string path)
{
    try
    {
        if (!string.IsNullOrEmpty(path))
        {
            byte[] file = (new WebClient()).DownloadData(baseAddress + path);
            return file;
        }
        else return new byte[0];
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

public static BitmapImage ConvertToBitmapImage(byte[] imageData)
{
    if (imageData == null || imageData.Length == 0) return null;
    var image = new BitmapImage();
    using (var mem = new MemoryStream(imageData))
    {
        mem.Position = 0;
        image.BeginInit();
        image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = null;
        image.StreamSource = mem;
        image.EndInit();
    }
    image.Freeze();
    return image;
}

private Task GetThumbnail(List<Model> models)
{
    Task.Run(() =>
    {
        foreach (var model in models)
        {
            try
            {
                model.ThumbnailBytes = GetByteArrayFromRelPath(model.ThumbnailPath);
            }
            catch (Exception) { }
        }
    });
    return null;
}

public byte[] ThumbnailBytes
{
    get { return _thumbnailBytes; }
    set
    {
        _thumbnailBytes = value;
        Thumbnail = ConversionHelper.ConvertToBitmapImage(_thumbnailBytes);
    }
}

0 个答案:

没有答案