UWP开发中两种网络图片缓存方法
通常情况下,我们的程序需要从服务器读取图片,但如果需要不止一次读取某一张图片的话,就需要做本地缓存了,这样既为用户省一点流量,又能显得你的APP很快。
假如你已经知道了某一张图片的地址,那么第一件事就是要把这张图片下载下来;当然如果是一次性读取的话,可以直接把图片地址给Image控件或者给Bitmapimage对象(实际上这二者是没有去别的),但这无法存到本地,只作为显示用;但是我们要做的是保存到本地,这样肯定是不行的。现在我们就要用到HTTP的东西了,请看下面的代码:
async static public Task<IInputStream> GetStreamAsync(string url)
{ httpClient = new HttpClient();
var response = await httpClient.GetInputStreamAsync(new Uri(url));
return response;
} async static public Task<IBuffer> 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<WriteableBitmap> 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(), , (int)buffer.Length); await stream2Write.FlushAsync();
stream.Seek(); await bi.SetSourceAsync(stream); wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
stream.Seek();
await wb.SetSourceAsync(stream); return wb;
}
}
else
{
return null;
}
}
catch
{
return null;
}
}
2.SoftwareBitmap
public async Task<SoftwareBitmap> 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, , 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();
}
}
}
怎么样,是不是很简单?
UWP开发中两种网络图片缓存方法的更多相关文章
- 说一说Web开发中两种常用的分层架构及其对应的代码模型
昨天妹子让我帮她解决个问题,本以为可以轻松搞定,但是打开他们项目的一瞬间,我头皮发麻.本身功能不多的一个小项目,解决方案里竟然有几十个类库.仅仅搞明白各个类库的作用,代码层次之间的引用关系就花了一个多 ...
- Python中两种处理错误方法的比较
我所说的处理错误的方法,其实是try:,except和raise这两种. 首先抛出一个实例, dictt={'a':1,'b':2,'c':3} try: if dictt['d']>1: #字 ...
- Cesium 中两种添加 model 方法的区别
概述 Cesium 中包含两种添加 model 的方法,分别为: 通过 viewer.entities.add() 函数添加 通过 viewer.scene.primitives.add() 函数添加 ...
- Mat中两种像素遍历方法比较
小白,入门中,不足其指正.刚刚接触opencv,从一个Matlab风格的编程环境突然跳转到C++,实在有些不适.单就pixels scanning花了好长时间研究.opencv-tutorials给出 ...
- python中两种拷贝目录方法的比较
首先是用python自己的api: shutil.copytree('./build/tested/doc', './build/tested/build/doc') 优点是改变平台时不需要修改代码, ...
- JAVA 中两种判断输入的是否是数字的方法__正则化_
JAVA 中两种判断输入的是否是数字的方法 package t0806; import java.io.*; import java.util.regex.*; public class zhengz ...
- jsp中两种include的区别【转】
引用文章:http://www.ibm.com/developerworks/cn/java/j-jsp04293/ http://www.cnblogs.com/lazycoding/archive ...
- IOS开发-几种截屏方法
IOS开发-几种截屏方法 1. UIGraphicsBeginImageContextWithOptions(pageView.page.bounds.size, YES, zoomSc ...
- GET和POST两种基本请求方法(转自博主--在途中#)
GET和POST两种基本请求方法的区别 GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通过req ...
随机推荐
- 【Swift学习】Swift编程之旅---扩展(二十四)
扩展就是向一个已有的类.结构体或枚举类型添加新功能,包含属性和方法,如果你定义了一个扩展向一个已有类型添加新功能,那么这个新功能对该类型的所有已有实例中都是可用的,即使它们是在你的这个扩展的前面定义的 ...
- 大话immutable.js
为啥要用immutable.js呢.毫不夸张的说.有了immutable.js(当然也有其他实现库)..才能将react的性能发挥到极致!要是各位看官用过一段时间的react,而没有用immutabl ...
- Android 手机上获取物理唯一标识码[转]
所有添加有谷歌账户的设备可以返回一个 ANDROID_ID 所有的CDMA设备对于 ANDROID_ID 和 TelephonyManager.getDeviceId() 返回相同的值(只要在设置时添 ...
- 【转载】HTTP 错误 500.19 - Internal Server Error
windows 2008下IIS7 安装ASP.NET 遇到如下错误: HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相关配置数据无效. ...
- 帝国cmsV6.6版数据表
信息表:每个模型都有以下六个表 phome_ecms_news 新闻系统模型-主表 phome_ecms_news_data_1 新闻系统模型-副表1 副表可无限增加 信息表 phome_ecms_n ...
- ASP.NET 的IP帮助类
个人网站地址: https://www.lesg.cn/netdaima/net/2016-239.html ASP.NET 的IP帮助类 在Web开发中会出现需要调用客户IP的方法: 一般调用方法就 ...
- 浅谈Oracle中物理结构(数据文件等。。。)与逻辑结构(表空间等。。。。。)
初始Oracle时很难理解其中的物理结构和逻辑结构,不明白内存中和硬盘中文件的区别和联系,我也是初学Oracle,这里就简单的谈谈我我看法. 首先,你需要明白的一点是:数据库的物理结构是由数据库的操作 ...
- jquery的ajax可以传入的三种参数类型
在jquery的ajax函数中,可以传入3种类型的数据 1.文本:"uname=alice&mobileIpt=110&birthday=1983-05-12" 2 ...
- 以【猫叫、老鼠跑、主人醒】为例子,使用 javascript 来实现 观察者模式 (有在线演示)
“猫叫.老鼠跑.主人醒”是一个很古老的话题了,大家也都有各自的想法和解决方案.我也是看了很多,一开始的时候是相当的迷糊,这个怎么就是面试题了?考的是啥呀,和编程有关系吗?又是猫又是老鼠的,晕死了.后来 ...
- JQuery读取XML文件
<?xml version="1.0" encoding="utf-8" ?> <taxrates> <taxrate id=&q ...