UWP开发中两种网络图片缓存方法

简介: 原文:UWP开发中两种网络图片缓存方法  通常情况下,我们的程序需要从服务器读取图片,但如果需要不止一次读取某一张图片的话,就需要做本地缓存了,这样既为用户省一点流量,又能显得你的APP很快。   假如你已经知道了某一张图片的地址,那么第一件事就是要把这张图片下载下来;当然如果是一次性读取的话,可以直接把图片地址给Image控件或者给Bitmapimage对象(实际上这二者是没有去别的),但这无法存到本地,只作为显示用;但是我们要做的是保存到本地,这样肯定是不行的。
原文: 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(), 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<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, 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();
                }
            }
        }

怎么样,是不是很简单?

目录
相关文章
|
3天前
|
监控 网络安全
LabVIEW开发干扰对无线网络基础设施进行隐蔽影响测试
LabVIEW开发干扰对无线网络基础设施进行隐蔽影响测试
|
3天前
|
机器学习/深度学习 传感器 算法
LabVIEW开发基于神经网络的自动汽车制动系统
LabVIEW开发基于神经网络的自动汽车制动系统
|
3天前
|
JSON 网络协议 调度
LabVIEW开发TCP网络通讯程序4
LabVIEW开发TCP网络通讯程序4
|
3天前
|
XML JSON 网络协议
LabVIEW开发TCP网络通讯程序3
LabVIEW开发TCP网络通讯程序3
|
3天前
|
网络协议 测试技术
LabVIEW开发TCP网络通讯程序2
LabVIEW开发TCP网络通讯程序2
|
3天前
|
网络协议
LabVIEW开发TCP网络通讯程序1
LabVIEW开发TCP网络通讯程序1
|
5天前
|
网络协议
LabVIEW 通过网络同步多台计算机系统时间的方法与例程
LabVIEW 通过网络同步多台计算机系统时间的方法与例程
|
8天前
|
监控 安全 网络安全
网络安全与信息安全:保护数据的重要性与方法
网络安全和信息安全是当今社会中不可或缺的话题。本文旨在探讨网络安全漏洞、加密技术和安全意识等方面的知识,以帮助读者更好地理解如何保护个人和机构的数据安全。
15 1
|
13天前
|
缓存 编解码
FFmpeg开发笔记(十四)FFmpeg音频重采样的缓存
FFmpeg在视频流重编码和音频重采样中使用缓存机制。在音频文件格式转换时,特别是对于帧长度不固定的格式如ogg、amr、wma,需处理重采样缓存。通过调用`swr_convert`,传入空输入和0大小来清空缓存。在`swrmp3.c`中,修改帧样本数处理,并在循环结束后添加代码以冲刷缓存。编译并运行程序,将ogg文件重采样为MP3,日志显示操作成功,播放转换后的文件确认功能正常。
FFmpeg开发笔记(十四)FFmpeg音频重采样的缓存
|
14天前
|
机器学习/深度学习 安全 网络安全
数字堡垒的构筑者:网络安全与信息安全的深层剖析构建高效微服务架构:后端开发的新趋势
【4月更文挑战第30天】在信息技术高速发展的今天,构建坚不可摧的数字堡垒已成为个人、企业乃至国家安全的重要组成部分。本文深入探讨网络安全漏洞的本质、加密技术的进展以及提升安全意识的必要性,旨在为读者提供全面的网络安全与信息安全知识框架。通过对网络攻防技术的解析和案例研究,我们揭示了防御策略的关键点,并强调了持续教育在塑造安全文化中的作用。