gpt4 book ai didi

android - 如何将图像保存到内部存储,然后在另一个 Activity 中显示?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:01:15 25 4
gpt4 key购买 nike

我在 Xamarin.Android 工作。我有两个 Activity 需要显示相同的图像。在第一个屏幕上,我从 Web URL 下载它并显示它,但我不想在第二个屏幕上做同样的事情。当它在第一个屏幕上下载时,我想将它保存到内部存储中,然后只需从那里检索它以在第二个 Activity 中显示。我该怎么做?

这是我在第一个 Activity 中使用的代码:

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);
});
}
}

现在保存图像,这是我受 this 启发所做的。 :

        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'

最佳答案

好的,这就是我让它工作的方式:

    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");

try
{
using (var os = new System.IO.FileStream(myPath.AbsolutePath, System.IO.FileMode.Create))
{
bm.Compress(Bitmap.CompressFormat.Png, 100, os);
}
}
catch (Exception ex)
{
System.Console.Write(ex.Message);
}

关于android - 如何将图像保存到内部存储,然后在另一个 Activity 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23131768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com