【问题标题】:Saving Image Retrieved from InputStream locally在本地保存从 InputStream 检索的图像
【发布时间】:2011-11-04 16:29:25
【问题描述】:

我使用以下代码从 url 检索图像并将其显示在活动中。

    InputStream is = (InputStream) new URL(url[0]).getContent();
    Drawable d = Drawable.createFromStream(is, "imagename");
    ImageView... 

现在我想在用户单击按钮时在本地保存此图像(Drawable d),以便我可以在另一个活动中再次显示它(以及其他一些任务)。

我想将其存储在应用文件夹本身而不是 SD 卡上。

我该怎么做?

谢谢! 香农

【问题讨论】:

  • 看我的回答。希望对您有所帮助。

标签: android inputstream drawable


【解决方案1】:

这将为您完成:

Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
FileOutputStream out = openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);

【讨论】:

  • 谢谢.. 这似乎有效。我在 LogCat 中没有收到错误,表明保存文件时出现问题。如果我想在另一个活动中访问该文件,如何引用该文件以及它保存在哪里(可绘制、原始等)?
  • 谢谢,这段代码完美地保存了文件!我想出了如何通过使用“InputStream is = openFileInput("imagenamesaved");”打开它来引用保存的文件。然后像我在上面的问题中那样处理它。这是有效的!太棒了,非常感谢!
【解决方案2】:

对于可绘制的另存为图像,我正在这样做,

Bitmap image_saved=BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);

FileOutputStream fOut=new FileOutputStream(path+"/"+fileName); 
// Here path is either sdcard or internal storage
image_saved.compress(Bitmap.CompressFormat.JPEG,100,fOut);
fOut.flush();
fOut.close();
image_saved.recycle(); // If no longer used..

但实际上,我建议您不要从 InputStream 转到 Drawable,而是从 InputStream 转到 File,然后从文件中加载图像。所以你可以保存第一个文件并在加载图像时使用它。

对于 url Inputstream 来写文件看这个教程Save binary file from URL

【讨论】:

  • 谢谢!我喜欢关于在本地下载图像并根据需要显示它的建议......这个教程很棒。我有几个问题...... 1)文件保存在哪里(可绘制,原始等)。如果答案是我想要的...您在哪里推荐以及如何引用本地目录的路径(可绘制、原始等) 2)如何在运行时引用文件?我是否只有一个已经位于本地的文件在运行时覆盖?
  • 没关系!我得到了答案。我对如何在运行时处理文件存在误解! DDMS 帮助我了解了文件结构以及我的文件保存在哪里!
  • 很好,因为您自己回答了您的问题。 :-)
【解决方案3】:

请查看此documentation 了解如何保存缓存文件,查看此documentation 了解一般内部文件存储。

【讨论】:

    【解决方案4】:

    经过测试的sn-p:

    InputStream is=null;
                try {
                    is = (InputStream) new URL(url).getContent();
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                Drawable d = Drawable.createFromStream(is, "profile_picture");
                Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
                FileOutputStream out=null;
                try {
                    out = getActivity().getApplicationContext().openFileOutput("profile_picture", getActivity().getApplicationContext().MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 2013-12-28
      • 2016-05-05
      • 1970-01-01
      • 2015-03-07
      • 2023-03-21
      • 2014-05-25
      • 2017-03-10
      相关资源
      最近更新 更多