其他分享
首页 > 其他分享> > android – 如何将图像保存到内部存储,然后在另一个活动上显示?

android – 如何将图像保存到内部存储,然后在另一个活动上显示?

作者:互联网

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

现在为了保存图像,这是我在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,file-io,xamarin-android,bitmapimage
来源: https://codeday.me/bug/20190629/1322130.html