博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UWP开发中两种网络图片缓存方法
阅读量:6434 次
发布时间:2019-06-23

本文共 5589 字,大约阅读时间需要 18 分钟。

原文:

  通常情况下,我们的程序需要从服务器读取图片,但如果需要不止一次读取某一张图片的话,就需要做本地缓存了,这样既为用户省一点流量,又能显得你的APP很快。

  假如你已经知道了某一张图片的地址,那么第一件事就是要把这张图片下载下来;当然如果是一次性读取的话,可以直接把图片地址给Image控件或者给Bitmapimage对象(实际上这二者是没有去别的),但这无法存到本地,只作为显示用;但是我们要做的是保存到本地,这样肯定是不行的。现在我们就要用到HTTP的东西了,请看下面的代码:

async static public Task
GetStreamAsync(string url) { httpClient = new HttpClient(); var response = await httpClient.GetInputStreamAsync(new Uri(url)); return response; } async static public Task
GetBufferAsync(string url) { httpClient = new HttpClient(); var ResultStr = await httpClient.GetBufferAsync(new Uri(url)); return ResultStr; }

这两个静态方法分别获取url地址的buffer数据和输入流。有了buffer或者stream之后就可以进行下一步-保存。

  当我们下载完成后,首先要做的很有可能是先显示出来,然后再保存,所以先把数据写入到图片对象中:

这里有两种方法:

1.WriteableBitmap

protected async Task
GetWriteableBitmapAsync(string url) { try { IBuffer buffer = await GetBufferAsync(url); if (buffer != null) { BitmapImage bi = new BitmapImage(); WriteableBitmap wb = null; Stream stream2Write; using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { stream2Write = stream.AsStreamForWrite(); await stream2Write.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length); await stream2Write.FlushAsync(); stream.Seek(0); await bi.SetSourceAsync(stream); wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight); stream.Seek(0); await wb.SetSourceAsync(stream); return wb; } } else { return null; } } catch { return null; } }

2.SoftwareBitmap

public async Task
GetSoftwareBitmapAsync(string url) { try { IInputStream inputStream = await GetSteramAsync(url); IRandomAccessStream memStream = new InMemoryRandomAccessStream(); await RandomAccessStream.CopyAsync(inputStream, memStream); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memStream); SoftwareBitmap sb = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); return sb; } catch { return null; } }

这两种都可以作为展示图像的数据源,其中WriteableBitmap可以直接给Image.Source , SoftwareBitmap这需要转为SoftwareBitmap:

         SoftwareBitmapSource sbs = new SoftwareBitmapSource();                sbs.SetBitmapAsync(sb);

接下来就是保存了:WriteableBitmap:

public async Task SaveImageAsync(WriteableBitmap image, string filename)        {            try            {                if (image == null)                {                    return;                }                Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;                if (filename.EndsWith("jpg"))                    BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;                else if (filename.EndsWith("png"))                    BitmapEncoderGuid = BitmapEncoder.PngEncoderId;                else if (filename.EndsWith("bmp"))                    BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;                else if (filename.EndsWith("tiff"))                    BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;                else if (filename.EndsWith("gif"))                    BitmapEncoderGuid = BitmapEncoder.GifEncoderId;                var folder = await _local_folder.CreateFolderAsync("images_cache", CreationCollisionOption.OpenIfExists);                var file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))                {                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);                    Stream pixelStream = image.PixelBuffer.AsStream();                    byte[] pixels = new byte[pixelStream.Length];                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,                              (uint)image.PixelWidth,                              (uint)image.PixelHeight,                              96.0,                              96.0,                              pixels);                    await encoder.FlushAsync();                }            }            catch            {            }        }
public async Task WriteToFileAsync(StorageFolder folder,SoftwareBitmap sb,string fileName)        {                       if (sb != null)            {                // save image file to cache                StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))                {                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);                    encoder.SetSoftwareBitmap(sb);                    await encoder.FlushAsync();                }            }        }

怎么样,是不是很简单?

转载地址:http://cehga.baihongyu.com/

你可能感兴趣的文章
新手学习Linux——rsync+shell脚本完成自动化备份
查看>>
WebView与JavaScript交互
查看>>
这些职场办公神器,你会喜欢的!
查看>>
Random随机数相关工具类
查看>>
.h file not found
查看>>
Shiro使用redis作为缓存(解决shiro频繁访问Redis)
查看>>
一分钟检测应用状态 | 企业应用健康扫描中心发布
查看>>
Visual Paradigm 教程[UML]:如何在序列图中使用持续时间约束?
查看>>
云计算数据管理的4个关键因素
查看>>
“重构”黑洞:26岁MIT研究生的新算法
查看>>
OpenStack运维面试(1)
查看>>
#翻译NO.4# --- Spring Integration Framework
查看>>
CentOS 7 yum方式快速安装MongoDB
查看>>
DBCP针对不同数据库的validationQuery
查看>>
mysql中varchar与integer的互转
查看>>
Varnish的性能调优
查看>>
linux solrcloud zookeeper分布式集群部署
查看>>
通过流进行字符集编码转换
查看>>
详细讲述STP过程【转自56cto.com】
查看>>
在Office 365 添加就地保留用户邮箱
查看>>