下载图像并保存在图库中?

Posted

技术标签:

【中文标题】下载图像并保存在图库中?【英文标题】:download image and save in gallery? 【发布时间】:2015-04-19 00:39:01 【问题描述】:

我从服务器得到响应,在我的响应中我得到图像,该响应的视图在列表视图中,现在我想要的是下面的图像我有一个下载图像的按钮,我想下载该图像和将其存储在图库中。下面是我的代码和响应。

JSON 响应..

 [
       
      "b_card":"http:\/\/www.webname.com\/uploaded\/users\/vcard\/8_ers.jpg"
          
       ]

MyBaseAdapter

 public class CustomAdapterBusinessCard extends BaseAdapter


private static Bitmap bmp;
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;

/*private static final String ADD_NAME="title_tag";
private static final String ADD_DESC="description";*/
private static final String ADD_IMAGE="b_card";




public CustomAdapterBusinessCard(Context context,ArrayList<HashMap<String,String>> listData) 
    this.context = context;
    this.listData=listData;
    aQuery = new AQuery(this.context);


@Override
public int getCount() 
    return listData.size();


@Override
public Object getItem(int position) 
    return listData.get(position);


@Override
public long getItemId(int position) 
    return position;



@Override
public View getView(final int position, View convertView, ViewGroup parent) 
    ViewHolder holder;
    if (convertView == null) 
        holder = new ViewHolder();
        convertView = LayoutInflater.from(context).inflate(R.layout.business_card, null);
        holder.propic = (ImageView) convertView.findViewById(R.id.imgvwbusinesscard);
        holder.btndownload=(Button) convertView.findViewById(R.id.dwnldbutton);
       // holder.txtproname = (TextView) convertView.findViewById(R.id.txtproducts);
       // holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidsearch);
        //holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtproductsdescription);
       holder.btndownload.setOnClickListener(new OnClickListener() 

        private String url;

        @Override
        public void onClick(View v) 

            url = listData.get(position).get("b_card");
            System.out.println("cheking url"+url);
            new DownloadImageAsyncTask().execute();
            /*try 
                bmp = getBitmapFromUrl(url);
             catch (IOException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            */

        
    );


        convertView.setTag(holder);
    else
        holder = (ViewHolder) convertView.getTag();
    


  /*  holder.txtproname.setText(listData.get(position).get(ADD_NAME));
    //holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
    holder.txtprofilecast.setText(listData.get(position).get(ADD_DESC));
   */

    holder.propic.setImageDrawable(Drawable.createFromPath(context.getExternalCacheDir() + File.separator
            + context.getResources().getString(R.string.app_name) + File.separator + "ImageName.png"));
    aQuery.id(holder.propic).image(listData.get(position).get(ADD_IMAGE),true,true,0,R.drawable.ic_launcher);



    // image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
    return convertView;







class ViewHolder
    ImageView propic;
    Button btndownload;
  //  TextView txtproname;
   // TextView txtproid;
  //  TextView txtprofilecast;




class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> 


         @Override
         protected Void doInBackground(Void... params)
         
             // TODO Auto-generated method stub
             downloadImages();
             return null;
         

         @Override
         protected void onPostExecute(Void result)
         
             // TODO Auto-generated method stub
             super.onPostExecute(result);

         

 
private void downloadImages()


    URL imageUrl; //your URL from which image to be downloaded
    String domain;
    try
    
        imageUrl = new URL("http://www.webname.com/web-service/b_card.php?user_id=8");

        HttpURLConnection urlConnection;
        try
        
            urlConnection = (HttpURLConnection) imageUrl.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();
            String path = context.getExternalCacheDir() + File.separator + context.getResources().getString(R.string.app_name);
            File f = new File(path);
            if (!f.exists())
            
                f.mkdirs();
            
            File file = new File(f, "ImageName.png"); // Here you can save the image with name and extension
            if (!file.exists())
            
                file.createNewFile();
            
            FileOutputStream fileOutput = new FileOutputStream(file);
            InputStream inputStream = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int bufferLength = 0; // used to store a temporary size of the
                                    // buffer
            while ((bufferLength = inputStream.read(buffer)) > 0)
            
                fileOutput.write(buffer, 0, bufferLength);
            
            fileOutput.close();
        
        catch (IOException e)
        
            e.printStackTrace();
        

    
    catch (MalformedURLException e)
    
        e.printStackTrace();
    


我的活动

public class BusinessCard extends ListActivity

private ArrayList<HashMap<String,String>> aList;

private String User_id;
JSONArray country_list=null;


private CustomAdapterBusinessCard adapter;
private ImageView bucard;
ImageLoader _DownImageLoader;

AQuery androidAQuery=new AQuery(this);
JSONArray state_list=null;
private static String BUSINESS_CARD_URL = "";
private static final String BUSINESS_CARD="b_card";

ArrayList<HashMap<String,String>> subcatagorydata;

@Override
protected void onCreate(Bundle savedInstanceState) 
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_view_businesscard);

    User_id=this.getIntent().getStringExtra("userids");
    System.out.println("for business card"+User_id);


    BUSINESS_CARD_URL="http://www.webname.com/web-service/b_card.php?user_id="+User_id;




    bucard=(ImageView)findViewById(R.id.imgvwbusinesscard);


    new LoadBusiness().execute();




class LoadBusiness extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> 

      ArrayAdapter<String> adaptercountry ;
    private ProgressDialog pDialog;
    private ArrayList<HashMap<String, String>> data;
    private String desc;
        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            pDialog = new ProgressDialog(BusinessCard.this);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
           // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(true);
            pDialog.show();

        
        protected ArrayList<HashMap<String,String>> doInBackground(String... args) 
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            data = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(BUSINESS_CARD_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) 
                try 
                    //JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node

                    //JSONArray data_array = new JSONArray(received);
                    country_list = new JSONArray(jsonStr);

                    // looping through All Contacts
                    for (int i = 0; i < country_list.length(); i++) 
                        JSONObject c = country_list.getJSONObject(i);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(BUSINESS_CARD, c.getString(BUSINESS_CARD));
                        /*map.put(PROFILE_VIEW_SUB_CATAGORY,c.getString(PROFILE_VIEW_SUB_CATAGORY));
                        map.put(PROFILE_VIEW_IMAGE,c.getString(PROFILE_VIEW_IMAGE));*/
                       // desc=country_list.getJSONObject(0).getJSONObject("description").toString();
                        /*JSONObject js=new JSONObject();
                        js.getString("description");
                        desc=js.toString();*/
                       // System.out.println("jsjsj"+desc);

                        data.add(map);

                    
                 catch (JSONException e) 
                    e.printStackTrace();
                
             else 
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            

            return data;
        
        protected void onPostExecute(ArrayList<HashMap<String,String>> result) 
            super.onPostExecute(result);
            pDialog.dismiss();


            if(aList == null)
            
                aList = new ArrayList<HashMap<String, String>>();
                aList.addAll(result);
                adapter = new CustomAdapterBusinessCard(getBaseContext(), result);
                setListAdapter(adapter);
            
            else
            
                aList.addAll(result);
                adapter.notifyDataSetChanged();
            
        
 

列表视图

   <RelativeLayout 
android:layout_
android:layout_
android:background="@android:color/white"
 >

       <ListView 
    android:layout_
    android:layout_
    android:id="@android:id/list"
    android:dividerHeight="1dp"

    ></ListView>


    </RelativeLayout>

列表项

   <LinearLayout 
        android:layout_
         android:layout_
         android:orientation="vertical" >
      <ImageView 
    android:layout_
    android:layout_
    android:id="@+id/imgvwbusinesscard"
    />
          <Button 
          android:layout_
          android:layout_
        android:text="Download"
        android:id="@+id/dwnldbutton"

      />

   </LinearLayout>

【问题讨论】:

保存图像使用此代码***.com/a/7887114/964741 我可以在我的基本适配器文件或活动中在哪里使用该功能?首先我需要下载然后想要存储 您要存储图像的位置...一旦从 url 下载图像,就会将位图传递给该函数。它将保存该图像。 我想将它存储在画廊中。我应该将该功能添加到我的基本适配器的 btn clikc 列表器中吗? 是的.. 图像下载完成后调用它 【参考方案1】:

我通过使用 AsyncTask 从 URL 下载图像来做到这一点。

  class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> 
   

            @Override
            protected Void doInBackground(Void... params)
            
                // TODO Auto-generated method stub
                downloadImages();
                return null;
            

            @Override
            protected void onPostExecute(Void result)
            
                // TODO Auto-generated method stub
                super.onPostExecute(result);

            

    

这是下载图片的功能,你可以从很多网站得到参考。

private void downloadImages()
    

        URL imageUrl; //your URL from which image to be downloaded
        String domain;
        try
        
            imageUrl = new URL("your URL");

            HttpURLConnection urlConnection;
            try
            
                urlConnection = (HttpURLConnection) imageUrl.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);
                urlConnection.connect();
                String path = getExternalCacheDir() + File.separator + getResources().getString(R.string.app_name);
                File f = new File(path);
                if (!f.exists())
                
                    f.mkdirs();
                
                File file = new File(f, "ImageName.png"); // Here you can save the image with name and extension
                if (!file.exists())
                
                    file.createNewFile();
                
                FileOutputStream fileOutput = new FileOutputStream(file);
                InputStream inputStream = urlConnection.getInputStream();
                byte[] buffer = new byte[1024];
                int bufferLength = 0; // used to store a temporary size of the
                                        // buffer
                while ((bufferLength = inputStream.read(buffer)) > 0)
                
                    fileOutput.write(buffer, 0, bufferLength);
                
                fileOutput.close();
            
            catch (IOException e)
            
                e.printStackTrace();
            

        
        catch (MalformedURLException e)
        
            e.printStackTrace();
        

    

然后在您的 Adapter 类中,您可以通过以下方式设置图像:

holder.propic.setImageDrawable(Drawable.createFromPath(getExternalCacheDir() + File.separator
    + getResources().getString(R.string.app_name) + File.separator + "ImageName.png"));  //Exact path where the image is saved.

希望对你有帮助。

【讨论】:

好的..当第一次运行应用程序时..按钮消失并且图像显示一半..然后按返回按钮..再次加载该页面..然后按钮出现并且图像消失了。 .and in logcat..java.net.MalformedURLException: Protocol not found: your URL 如何设置 holder.propic.setImageDrawable(Drawable.createFromPath(context.getExternalCacheDir() + File.separator + context.getResources().getString(R.string.app_name) + File.separator + "ImageName.png"));在下载图像之前? 在不下载图片之前设置默认图片,点击下载按钮后设置下载的图片。 现在两者都正确显示,但是..仍然在 logcat 中显示 java.net.MalformedURLException: Protocol not found: your URL ..我该怎么办?你能推荐一下兄弟吗? 请先学习基础知识.. imageUrl = new URL("your URL");.... 您必须在"位置添加要从中下载图像的图像URL你的网址”【参考方案2】:

使用此代码从 URL 下载图像

public Bitmap getBitmapFromURL(String src) 
   try 
       java.net.URL url = new java.net.URL(src);
       HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
       connection.setDoInput(true);
       connection.connect();
       InputStream input = connection.getInputStream();
       Bitmap myBitmap = BitmapFactory.decodeStream(input);
       return myBitmap;
    catch (IOException e) 
       e.printStackTrace();
       return null;
   

【讨论】:

【参考方案3】:

使用以下代码从url下载图片:

private static Bitmap getBitmapFromUrl(String imgURL)
                throws IOException 

            URL IMGURL = new URL(imgURL);           
            HttpURLConnection conn = (HttpURLConnection) IMGURL.openConnection();
            conn.setDoInput(true);
            conn.connect();

            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);

            InputStream is = conn.getInputStream();
            bmp = BitmapFactory.decodeStream(is);

            return bmp;
        

它会返回一个准备好保存到存储中的位图。

【讨论】:

在doInBackground中,在你得到图片的url之后。 我不明白你..因为我的 asyncktask 在我的活动类中..我的按钮在我的适配器类中..两者都是不同的文件.. String url = c.getString(BUSINESS_CARD) // 这里你会得到图片的url。现在将它传递给 getBitmapFromUrl(String url)。 好的。在适配器的按钮单击方法(onclick)中,检索图像的url。 在 onclick 中使用代码:String url = listData.get(position).get(b_card);

以上是关于下载图像并保存在图库中?的主要内容,如果未能解决你的问题,请参考以下文章

如何检查图片是不是存在于图库中?

从图库中选择图像并保存以备将来使用

如何从图库(Android Studio)中选择并保存图像?

将图库图像保存到手机/平板电脑

如何从图库中选择图像并保存到 xamarin 中的 sql 数据库

iOS:从网址下载视频并保存在图库中......?