如何压缩图像但不使用Xamarin Android调整大小?

时间:2015-05-27 22:36:04

标签: c# xamarin xamarin.android

我从服务器获取的图像大约15MB,但我想保持纵横比但是压缩文件的大小,因为我正在加载大小相同的多个文件?这些图像下载为BitMaps和Used SetImageBitmap以显示图像

2 个答案:

答案 0 :(得分:1)

您可以将图像转换为jpeg或png来完成此操作。这是Bitmap到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;
    }
}

答案 1 :(得分:-1)

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