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();
                }
            }
        }

何以,是否非常粗大略?

本文由金沙APP发布于金沙APP,转载请注明出处:UWP开发中两种网络图片缓存方法

上一篇:手把手教你搞懂Android反编译 下一篇:没有了
猜你喜欢
热门排行
精彩图文