[英]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.