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

时间:2014-04-17 11:20:59

标签: android file-io xamarin.android bitmapimage

我在Xamarin.Android工作。我有两个活动需要显示相同的图像。在第一个屏幕上,我从网址下载并显示它,但我不想在第二个屏幕上执行相同操作。我想在第一个屏幕上下载后将其保存到内部存储,然后只需从那里检索它以显示第二个活动。我怎么能这样做?

以下是我在第一项活动中使用的代码:

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'

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

Bitmap的compress方法将OutputStream的对象作为第三个参数,您传递的是FileOutputStream(从OutputStream驱动)。您可以尝试将OutputStream的对象传递给它,看看是否能解决问题。

答案 2 :(得分:0)

我认为这是你来回转换的方式:

using (var stream = new Java.Net.URL(uriString).OpenConnection().InputStream)
{
     bitmap = await BitmapFactory.DecodeStreamAsync(stream);
}

using (var stream = new Java.Net.URL(myPath.Path).OpenConnection().OutputStream)
{
    await bitmap.CompressAsync(Bitmap.CompressFormat.Png, 80, stream);
}

答案 3 :(得分:0)

如果你想把它保存到内部存储,它不会显示在图库中

public static void SaveBitmapToInternalStorage(this Context context, Bitmap bitmap, string filename, string directory)
    {
        //can change directory as per need
        if (directory != null || directory != "") directory = "/" + directory;
        var imagesDir = context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures+ directory);
        if (!imagesDir.Exists()) imagesDir.Mkdirs();
        var jFile = new Java.IO.File(imagesDir, filename);
        var filePath = jFile.AbsoluteFile.ToString();

        System.IO.FileStream output = null;
        using (output = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
        {
            bitmap.Compress(Bitmap.CompressFormat.Jpeg, 90, output);
        }
        output.Close();            
    }

并检索保存的图像 注意:文件名和目录应该相同才能检索相同的文件

public static Drawable GetDrawableFromInternalStorage(this Context context, string fileName, string directory)
    {
        //return drawable for imagename from internal storage
        if (directory != null || directory != "") directory = "/" + directory;
        var imagesDir = context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures + directory);
        if (!imagesDir.Exists()) return null;
        var jFile = new Java.IO.File(imagesDir, fileName);

        if (jFile.Exists())
        {
            var img = Drawable.CreateFromPath(jFile.ToString());
            return img;
        }
        return null;
    }

并将图像保存到图库

public static bool SaveImageToGallery(this Context context, Bitmap bmp, string directory)
    {
        // First save the picture
        string storePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + File.Separator + directory;
        File imgDir = new File(storePath);
        if (!imgDir.Exists()) imgDir.Mkdir();
        string fileName = System.DateTime.Today.ToLongDateString() + ".jpg";
        File file = new File(imgDir, fileName);
        try
        {
            var uri = Android.Net.Uri.FromFile(file);
            var os = context.ContentResolver.OpenOutputStream(uri);
            //Compress and save pictures by io stream
            bool isSuccess = bmp.Compress(Bitmap.CompressFormat.Jpeg, 60, os);
            os.Flush();
            os.Close();

            //Update the database by sending broadcast notifications after saving pictures                
            context.SendBroadcast(new Intent(Intent.ActionMediaScannerScanFile, uri));
            return isSuccess;
        }
        catch (IOException e) { }
        return false;
    }

如果您想创建唯一的文件名以保存到图库,则

File file = File.CreateTempFile(
                "Img_",  /* prefix */
                ".jpg",         /* suffix */
                imgDir    /* directory */);