如何压缩图像,但不调整它使用Xamarin Android

本文关键字:调整 Android Xamarin 何压缩 压缩 图像 | 更新日期: 2023-09-27 17:50:59

我从服务器得到一个图像,这是相当大的15MB左右,但我想保持宽高比,但压缩文件的大小,因为我正在加载多个文件,大约相同的大小?这些图像被下载为bitmap,并使用SetImageBitmap来显示图像

如何压缩图像,但不调整它使用Xamarin Android

您可以通过将图像转换为jpeg或png来实现这一点。这是位图到PNG转换例程的快速而粗糙的实现:

public string ResizeImage(string sourceFilePath)
{
    Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile (sourceFilePath);
    string newPath = sourceFilePath.Replace(".bmp", ".png");
    using (var fs = new FileStream (newPath, FileMode.OpenOrCreate)) {
        bmp.Compress (Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
    }
    return newPath;
}

它对文件扩展名做了假设,但可以很容易地修改。

下面是我用来验证压缩的完整示例:

public class MainActivity : Activity
{
    public const string BITMAP_URL = @"http://www.openjpeg.org/samples/Bretagne2.bmp";

    public string ResizeImage(string sourceFilePath)
    {
        Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile (sourceFilePath);
        string newPath = sourceFilePath.Replace(".bmp", ".png");
        using (var fs = new FileStream (newPath, FileMode.OpenOrCreate)) {
            bmp.Compress (Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
        }
        return newPath;
    }
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.Main);
        Button button = FindViewById<Button> (Resource.Id.myButton);
        button.Click += delegate {
            System.Threading.Tasks.Task.Run( () => {
                RunOnUiThread( () => Toast.MakeText(this, "Downloading file", ToastLength.Long).Show());
                string downloadFile = DownloadSourceImage(BITMAP_URL);
                RunOnUiThread( () => Toast.MakeText(this, "Rescaling image: " + downloadFile, ToastLength.Long).Show());
                string convertedFile = ResizeImage(downloadFile);
                var bmpFileSize = (new FileInfo(downloadFile)).Length;
                var pngFileSize = (new FileInfo(convertedFile)).Length;
                RunOnUiThread( () => Toast.MakeText(this, "BMP is " + bmpFileSize + "B. PNG is " + pngFileSize + "B.", ToastLength.Long).Show());
            });
        };
    }
    public string DownloadSourceImage(string url)
    {
        System.Net.WebClient client = new System.Net.WebClient ();
        string fileName = url.Split ('/').LastOrDefault ();
        string downloadedFilePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, fileName);
        if (File.Exists (downloadedFilePath) == false) {
            client.DownloadFile (url, downloadedFilePath);
        }
        return downloadedFilePath;
    }
}

您可以使用其他文件格式压缩图像(例如:jpeg)。或者您可以在保持宽高比的同时调整图像的大小。