首页 > 解决方案 > 如何在不使用 ImageView 的情况下从 API 端点下载图像或位图?

问题描述

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

到目前为止,我已经尝试使用 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);
}

标签: javaandroidandroid-studioandroid-volleyokhttp

解决方案


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

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

推荐阅读