直接在Android中的字节数组中使用JPEG

时间:2015-06-02 11:43:26

标签: android bitmap xamarin jpeg

我试图在列表中显示大约100个JPEG。它们是77KB的小文件,但如果我使用BitmapFactory.decodeByteArray,文件将被解压缩并变为1.6MB。当我尝试加载超过100个文件~160MB时,问题变得很明显。

我使用BitmapFactory.compress将图像缓存到持久存储,但我想将它们加载为JPEG并以这种方式使用它们。

我该怎么做?

目前我正在保存/存储这样的图像:

    public void SaveBitmapAsJpeg (Bitmap bitmap, string imageName)
    {
        lock (Locker) {
            var FilePath = System.IO.Path.Combine(ImageDirectoryPath, imageName);

            using (var Stream = new FileStream (FilePath, FileMode.Create)) 
            {
                const int ImageQuality = 100;
                bitmap.Compress(Bitmap.CompressFormat.Jpeg, ImageQuality, Stream);
            }

        }
    }

    /** Returns the file if it exists. Otherwise null. */
    public async Task<Bitmap> GetImageBitmap (string imageName)
    {

        var FilePath = System.IO.Path.Combine(ImageDirectoryPath, imageName);

        if (Directory.Exists (ImageDirectoryPath) == true) 
        {
            if (File.Exists(FilePath))
            {
                return await BitmapFactory.DecodeFileAsync (FilePath);
            }
        }

        return null;

    }

为了加载图像,我检查它是否被缓存,如果没有,请下载并缓存(保存到&#34;磁盘&#34;)文件:

/** Returns the cached image file, or if not found downloads and stores the image. */
private async Task<Bitmap> GetCachedImageOrDownloadAndStore (SimplePlaylist playlist) 
    {
        var Bitmap = await ImageStorage.Instance.GetImageBitmap (playlist.Id);
        if (Bitmap != null) 
        {
            return Bitmap;
        }
        else // Cannot find the cached image file
        {
        // download album art
        var Art = await DownloadAlbumArtForPlaylist(playlist);

        // Store the file
        ImageStorage.Instance.SaveBitmapAsPng(Art, playlist.Id);

    return Art;
}

下载JPEG的方法返回一个位图,因为我使用BitmapDrawables来显示它们。我不知道如何以其他方式做到这一点。

public async static Task<Bitmap> GetImageBitmapFromUrl(string url)
        {
            Bitmap imageBitmap = null;
            byte[] ImageBytes = null;

            var HttpResponseMessage = await AppController.Instance.HttpClient.GetAsync (url);
            await HttpResponseMessage.EnsureSuccessStatusCodeAsync();

            ImageBytes = await HttpResponseMessage.Content.ReadAsByteArrayAsync ();

            if (ImageBytes != null && ImageBytes.Length > 0)
            {
                imageBitmap = BitmapFactory.DecodeByteArray(ImageBytes, 0, ImageBytes.Length);
            }

            return imageBitmap;
        }

0 个答案:

没有答案
相关问题