我正在使用Xamarin.Android。我有两个活动,需要在它们上面显示相同的图像。在第一个屏幕上,我从Web URL下载并显示它,但我不想在第二个屏幕上重复这样做。我想在第一个屏幕上下载时将其保存到内部存储,并从那里简单地检索它以在第二个活动中显示。我该怎么做?
这是我在第一个活动中使用的代码:
现在要保存图像,这是我受到这个启发所做的事情:
然而,这段代码无法编译,当我调用
这是我在第一个活动中使用的代码:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
this.SetContentView (Resource.Layout.Main);
String uriString = this.GetUriString();
WebClient web = new WebClient ();
web.DownloadDataCompleted += new DownloadDataCompletedEventHandler(web_DownloadDataCompleted);
web.DownloadDataAsync (new Uri(uriString));
}
void web_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error != null)
{
RunOnUiThread(() =>
Toast.MakeText(this, e.Error.Message, ToastLength.Short).Show());
}
else
{
Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);
// THIS IS WHERE I NEED TO SAVE THE IMAGE IN INTERNAL STORAGE //
RunOnUiThread(() =>
{
ProgressBar pb = this.FindViewById<ProgressBar> (Resource.Id.custLogoProgressBar);
pb.Visibility = ViewStates.Gone;
ImageView imgCustLogo = FindViewById<ImageView>(Resource.Id.imgCustLogo);
imgCustLogo.SetImageBitmap(bm);
});
}
}
现在要保存图像,这是我受到这个启发所做的事情:
Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);
ContextWrapper cw = new ContextWrapper(this.ApplicationContext);
File directory = cw.GetDir("imgDir", FileCreationMode.Private);
File myPath = new File(directory, "test.png");
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(myPath);
bm.Compress(Bitmap.CompressFormat.Png, 100, fos);
fos.Close();
}
catch (Exception ex)
{
System.Console.Write(ex.Message);
}
然而,这段代码无法编译,当我调用
bm.Compress()
时会出现异常。它提示:Error CS1503: Argument 3: cannot convert from 'Java.IO.FileOutputStream' to 'System.IO.Stream'