[英]How to Compress Image but not resize it Using Xamarin Android?
我正在從大約15MB的很大的服務器上獲取圖像,但是我想保持寬高比但要壓縮文件的大小,因為我要加載多個大小相同的文件? 這些圖像以BitMaps的形式下載,並用於SetImageBitmap來顯示圖像
您可以通過將圖像轉換為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)壓縮圖像。 或者,您可以在保持寬高比的同時調整圖像大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.