2015-05-27 17 views
0

我从一个服务器上获得一个图像,大小约为15MB,但我想保持长宽比但压缩文件的大小,因为我正在加载大约相同大小的多个文件?这些图像被下载为BitMaps和使用SetImageBitmap来显示图像如何压缩图像但不调整其大小使用Xamarin Android?

+0

为了澄清,你想在磁盘上压缩文件的大小或减少一般图像的尺寸(宽度和高度)? – matthewrdev

+0

我只想压缩文件大小,而不是更改尺寸。 – Ash

回答

-1

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

1

你可以通过将图像转换为JPEG或PNG来做到这一点。这是快速和肮脏的实施位图PNG转换例程的:

​​

它的前提上的文件扩展名,但可以很容易修改。

这里是我用来验证压缩的全样本:

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; 
    } 
} 
相关问题