如何将图像URL转换为Drawable Int

时间:2017-08-23 04:12:02

标签: android json

早安所有!!!!

我正在尝试在Imageview中显示图像。但我的要求是,我需要以Drawable整数格式显示图像。我从服务器获取数据并以url格式获取图像..

For ex :http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg

我想以Drawable格式转换此图片。

这是我的代码

这是我的界面

 public interface ECCardData<T> {

    @DrawableRes
    Integer getMainBackgroundResource();

    @DrawableRes
    Integer getHeadBackgroundResource();

    List<T> getListItems();
}

我的Getter和Setter

     private Integer headBackgroundResource;

public Integer getHeadBackgroundResource() {
        return headBackgroundResource;
    }

    public void setHeadBackgroundResource(Integer headBackgroundResource) {
        this.headBackgroundResource = headBackgroundResource;
    }

我设置图片的代码

Integer drawableRes = dataset.get(position).getHeadBackgroundResource();
    if (drawableRes != null) {
        headView.setHeadImageBitmap(BitmapFactory.decodeResource(pagerContainer.getResources(), drawableRes, new BitmapFactoryOptions()));
    }

这是我的解析

 public static ArrayList<CardData> ParseCraft(String response) throws JSONException {


        ArrayList<CardData> alUser = new ArrayList<>();

        JSONObject jsonRoot = new JSONObject(response);

        JSONArray parentArray = jsonRoot.getJSONArray("products");

        for (int j = 0; j < parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            CardData user = new CardData();

            user.setHeadTitle(finalObject.getString("product"));
            user.setPersonName(finalObject.getString("product_code"));

            JSONObject productJsonObject = finalObject.getJSONObject("main_pair");
            JSONObject productJsonObject1 = productJsonObject.getJSONObject("detailed");

            user.setHeadBackgroundResource(productJsonObject1.getString("image_path"));



            alUser.add(user);
        }

        return alUser;
    }

我的json回复

{
"products": [
    {
        "product_id": "863",
        "product": "LAVA 4G CONNECT M1",
        "company_name": "SAPTHAGIRI MOBILES",
        "age_verification": "N",
        "age_limit": "0",
        "product_code": "SGMM00044",
        "product_type": "P",
        "status": "A",
        "company_id": "34",
        "approved": "Y",
        "list_price": "0.00",
        "amount": "2",
        "weight": "0.000",
        "length": "0",
        "width": "0",
        "height": "0",
        "shipping_freight": "0.00",
        "low_avail_limit": "0",
        "timestamp": "1492758588",
        "updated_timestamp": "1500273558",
        "usergroup_ids": "0",
        "is_edp": "N",
        "edp_shipping": "N",
        "unlimited_download": "N",
        "tracking": "B",
        "free_shipping": "N",
        "zero_price_action": "R",
        "is_pbp": "N",
        "is_op": "N",
        "is_oper": "N",
        "is_returnable": "Y",
        "return_period": "10",
        "avail_since": "0",
        "out_of_stock_actions": "N",
        "localization": "",
        "min_qty": "0",
        "max_qty": "0",
        "qty_step": "0",
        "list_qty_count": "0",
        "tax_ids": "",
        "options_type": "P",
        "exceptions_type": "F",
        "details_layout": "default",
        "shipping_params": "a:5:{s:16:\"min_items_in_box\";i:0;s:16:\"max_items_in_box\";i:0;s:10:\"box_length\";i:0;s:9:\"box_width\";i:0;s:10:\"box_height\";i:0;}",
        "facebook_obj_type": "activity",
        "buy_now_url": "",
        "cod": "N",
        "price": "3094.000000",
        "category_ids": [
            295
        ],
        "position": "0",
        "seo_name": "lava-4g-connect-m1",
        "seo_path": "166/234/295",
        "average_rating": null,
        "discussion_type": "D",
        "discussion_thread_id": "619",
        "main_category": 295,
        "main_pair": {
            "pair_id": "2577",
            "image_id": "0",
            "detailed_id": "3266",
            "position": "0",
            "detailed": {
                "object_id": "863",
                "object_type": "product",
                "image_path": "http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "alt": "",
                "image_x": "635",
                "image_y": "476",
                "http_image_path": "http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "https_image_path": "https://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "absolute_path": "/home/mymartmycart/public_html/images/detailed/3/4G_CONNECT_M1.jpeg",
                "relative_path": "detailed/3/4G_CONNECT_M1.jpeg"
            }
        },
        "base_price": "3094.000000",
        "selected_options": [],
        "has_options": false,
        "product_options": [],
        "discounts": {
            "A": 0,
            "P": 0
        },
        "product_features": [],
        "qty_content": []
    }

6 个答案:

答案 0 :(得分:3)

您可以使用协程在后台进行此工作:

    private fun loadImageFromWebUrl(url: String?) {
    lifecycleScope.launch(Dispatchers.IO) {
        val image  = try {
            val iStream = java.net.URL(url).content as InputStream
            Drawable.createFromStream(iStream, "src name")
        } catch (e: Exception) {
            null
        }

        image?.let {
            withContext(Dispatchers.Main){
                imageView.setImageDrawable = image 
            }
        }
    }
}

答案 1 :(得分:2)

此代码可用于将服务器图像网址转换为位图

 String drawableRes="http://kartpay.biz/api/v1/file/banner/IHMOcSHU7yoTVOkwYi1bOOz8shrXXrJhayCPFO17.jpeg"
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            URL url = new URL(drawableRes);
            headView.setHeadImageBitmap(BitmapFactory.decodeStream((InputStream)url.getContent()));
        } catch (IOException e) {
            //Log.e(TAG, e.getMessage());
        }

答案 2 :(得分:0)

我认为无法将图片网址转换为drawable int

您可以使用lib来显示来自网址的图片尝试

<强> 1。滑行

您可以使用Glide library从网址加载图片,查看下面的代码,它可以帮助您以简单的方式

编译这个库

  compile 'com.github.bumptech.glide:glide:4.0.0'

加载像这样的图像

RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_placeholder);
requestOptions.error(R.drawable.ic_error);

Glide.with(context)
     .setDefaultRequestOptions(requestOptions)
     .load(mainMenuDataModelArrayList.get(position)
     .getIMG()).into(holder.imageView);

<强> 2。 use picasso

编译这个库

compile 'com.squareup.picasso:picasso:2.5.2'

加载像这样的图像

Picasso.
  with(context).
  load(url).
  into(imageview);

或尝试此

 new DownloadImage(imamgeview).execute(url);

创建异步任务

public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImage(ImageView bmImage) {
    this.bmImage = (ImageView ) bmImage;
}

protected Bitmap doInBackground(String... urls) {
    String urldisplay = urls[0];
    Bitmap mIcon11 = null;
    try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
    } catch (Exception e) {
        Log.d("Error", e.getStackTrace().toString());

    }
    return mIcon11;
}

protected void onPostExecute(Bitmap result) {
    bmImage.setImageBitmap(result);
}
}

答案 3 :(得分:0)

可以使用Picasso库:

添加gradle:

compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load("http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg").into(imageView);

更多信息http://square.github.io/picasso/

答案 4 :(得分:0)

您可以通过以下代码

将图片从服务器网址下载到图片视图
public static Drawable LoadImageFromWebURL(String url) {
try {
    InputStream iStream = (InputStream) new URL(url).getContent();
    Drawable drawable = Drawable.createFromStream(ist, "src name");
    return drawable;
} catch (Exception e) {
    return null;
}}

您还可以使用第三方库将图像下载到直接imageView

compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load("image web url").into(imageView);

答案 5 :(得分:0)

我修改了这个库来做到这一点。 https://github.com/upendra-bajpai/expanding-collection-network/ 如果您有任何困难,可以在此处提出问题。 您可以在此处传递URL代替资源数据。