【问题标题】:How do I download an image or bitmap from an API endpoint without using ImageView?如何在不使用 ImageView 的情况下从 API 端点下载图像或位图?
【发布时间】:2020-11-20 13:15:19
【问题描述】:

我正在尝试在 android(java) 中使用 Volleyokhttp3 从端点下载图像,有一些方法可以表明ImageView 中的图像,有没有办法可以从 API 端点下载图像,并将其保存到名为 images 的子文件夹中的 assets 文件夹中。我已经有一段时间了,有点像 Volley 和 okhttp 的初学者。如果有人可以帮助我,那就太好了。

到目前为止,我已经尝试过使用 ImageRequest,

public void getImages(String url) {
    RequestQueue mRequestQueue = Volley.newRequestQueue(this);

    ImageRequest request = new ImageRequest("url",
            response -> {

            }, 0, 0, null,
            error -> {

            }) {
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("param1", "num1");
            params.put("param2", "num2");
            return params;
        }
    };
    mRequestQueue.add(request);
}

【问题讨论】:

  • 不,您不能保存到资产文件夹,因为它是只读的。为什么不保存到普通文件存储?

标签: java android android-studio android-volley okhttp


【解决方案1】:

如 cmets 中所述,无法修改资产文件夹。考虑将其保存在本地存储中

 protected Uri saveImageToInternalStorage(Bitmap bitmap){

    ContextWrapper wrapper = new ContextWrapper(getApplicationContext());

    File file = wrapper.getDir("Images",MODE_PRIVATE);

    file = new File(file, System.currentTimeMillis()+"_yourFileUnique"+".jpg");

    try{
        OutputStream stream = null;
        stream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
        stream.flush();
        stream.close();

    }catch (IOException e) // Catch the exception
    {
        e.printStackTrace();
    }
    Uri savedImageURI = Uri.parse(file.getAbsolutePath());
    return savedImageURI;
}

【讨论】:

  • 位图实例从何而来?如果您下载图像文件,则没有位图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 2018-11-17
  • 2019-03-25
  • 2010-12-08
相关资源
最近更新 更多