下载图像并保存在画廊? [英] download image and save in gallery?
问题描述
我收到来自服务器,并在我得到的图像我的回应的反应,该反应的观点是在列表视图,现在我想的是下面的图片,我有下载图像的一个按钮,我想下载该图像,它存储在gallery..below是我的code和响应。
JSON响应..
[
{
b_card:HTTP:\\ / \\ / www.webname.com \\ /上传\\ /用户\\ /名片\\ /8_ers.jpg
}
]
MyBaseAdapter
公共类CustomAdapterBusinessCard延伸BaseAdapter {
私有静态BMP位图;
私人上下文的背景下;
私人的ArrayList<&HashMap的LT;字符串,字符串>>的ListData;
私人AQuery aQuery;/ *私有静态最后弦乐ADD_NAME =title_tag;
私有静态最后弦乐ADD_DESC =说明; * /
私有静态最后弦乐ADD_IMAGE =b_card;
公共CustomAdapterBusinessCard(上下文的背景下,ArrayList的<&HashMap的LT;字符串,字符串>>的ListData){
this.context =背景;
this.listData =的ListData;
aQuery =新AQuery(this.context);
}@覆盖
公众诠释的getCount(){
返回listData.size();
}@覆盖
公共对象的getItem(INT位置){
返回listData.get(位置);
}@覆盖
众长getItemId(INT位置){
返回的位置;
}
@覆盖
公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
ViewHolder持有人;
如果(convertView == NULL){
持有人=新ViewHolder();
convertView = LayoutInflater.from(上下文).inflate(R.layout.business_card,NULL);
holder.propic =(ImageView的)convertView.findViewById(R.id.imgvwbusinesscard);
holder.btndownload =(按钮)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(新OnClickListener(){ 私人字符串URL; @覆盖
公共无效的onClick(视图v){ URL = listData.get(位置)获得(b_card);
的System.out.println(cheking网址+网址);
新DownloadImageAsyncTask()执行();
/ *尝试{
BMP = getBitmapFromUrl(URL);
}赶上(IOException异常五){
// TODO自动生成catch块
e.printStackTrace();
} * / }
});
convertView.setTag(保持器);
}其他{
支架=(ViewHolder)convertView.getTag();
}
/ * holder.txtproname.setText(listData.get(位置)获得(ADD_NAME));
//holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(位置)获得(ADD_DESC));
* / holder.propic.setImageDrawable(Drawable.createFromPath(context.getExternalCacheDir()+文件分割符
+ context.getResources()的getString(R.string.app_name)+文件分割符+ImageName.png));
aQuery.id(holder.propic).image(listData.get(position).get(ADD_IMAGE),true,true,0,R.drawable.ic_launcher); //图片参数:1:内存缓存,2:文件缓存,3:目标宽度,4:备用图片
返回convertView;}类ViewHolder {
ImageView的propic;
按钮btndownload;
// TextView的txtproname;
// TextView的txtproid;
// TextView的txtprofilecast;}
类DownloadImageAsyncTask扩展的AsyncTask<太虚,太虚,太虚>
{ @覆盖
保护无效doInBackground(无效... PARAMS)
{
// TODO自动生成方法存根
downloadImages();
返回null;
} @覆盖
保护无效onPostExecute(虚空结果)
{
// TODO自动生成方法存根
super.onPostExecute(结果); } }
私人无效downloadImages()
{ 网址图片网址; //您的网址从图像被下载
字符串域;
尝试
{
图片网址=新的URL(http://www.webname.com/web-service/b_card.php?user_id=8); HttpURLConnection类URLConnection的;
尝试
{
URLConnection的=(HttpURLConnection类)imageUrl.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(真);
urlConnection.connect();
字符串路径= context.getExternalCacheDir()+文件分割符+ context.getResources()的getString(R.string.app_name)。
文件f =新的文件(路径);
如果(!f.exists())
{
f.mkdirs();
}
档案文件=新的文件(FImageName.png); //在这里你可以保存图像用名和扩展名
如果(!file.exists())
{
file.createNewFile();
}
FileOutputStream中fileOutput =新的FileOutputStream(文件);
为InputStream的InputStream = urlConnection.getInputStream();
字节[]缓冲区=新的字节[1024];
INT BufferLength中= 0; //用于存储的临时尺寸
//缓冲区
而(量(bufferLength = inputStream.read(缓冲液))大于0)
{
fileOutput.write(缓冲液,0,BufferLength中);
}
fileOutput.close();
}
赶上(IOException异常E)
{
e.printStackTrace();
} }
赶上(MalformedURLException的E)
{
e.printStackTrace();
}}
}
MyActivity
公共类的businesscard扩展ListActivity {私人的ArrayList<&HashMap的LT;字符串,字符串>>一个列表;私人字符串USER_ID;
JSONArray COUNTRY_LIST = NULL;
私人CustomAdapterBusinessCard适配器;
私人ImageView的bucard;
ImageLoader的_DownImageLoader;AQuery androidAQuery =新AQuery(本);
JSONArray state_list = NULL;
私人静态字符串BUSINESS_CARD_URL =;
私有静态最后弦乐BUSINESS_CARD =b_card;ArrayList的<&HashMap的LT;字符串,字符串>> subcatagorydata;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
// TODO自动生成方法存根
super.onCreate(savedInstanceState);
的setContentView(R.layout.list_view_businesscard); USER_ID = this.getIntent()getStringExtra(用户ID);
的System.out.println(名片+ USER_ID);
BUSINESS_CARD_URL =http://www.webname.com/web-service/b_card.php?user_id=+ USER_ID;
bucard =(ImageView的)findViewById(R.id.imgvwbusinesscard);
新LoadBusiness()执行();
}类LoadBusiness扩展的AsyncTask<字符串,字符串的ArrayList<&HashMap的LT;字符串,字符串>>> { ArrayAdapter<串GT; adaptercountry;
私人ProgressDialog pDialog;
私人的ArrayList<&HashMap的LT;字符串,字符串>>数据;
私人字符串说明;
@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(BusinessCard.this);
pDialog.setMessage(正在加载...);
pDialog.setIndeterminate(假);
// pDialog.setIndeterminateDrawable(getResources()getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(真);
pDialog.show(); }
保护的ArrayList<&HashMap的LT;字符串,字符串>> doInBackground(字符串参数... args){
SH的ServiceHandler =新的ServiceHandler(); //制作到URL的请求和响应得到
数据=新的ArrayList<&HashMap的LT;字符串,字符串>>();
字符串jsonStr = sh.makeServiceCall(BUSINESS_CARD_URL,ServiceHandler.GET); Log.d(回应:,>中+ jsonStr); 如果(jsonStr!= NULL){
尝试{
// JSONObject的jsonObj =新的JSONObject(jsonStr); //获取JSON数组节点 // JSONArray data_array中=新JSONArray(收);
COUNTRY_LIST =新JSONArray(jsonStr); //通过所有联系人循环
的for(int i = 0; I< country_list.length();我++){
JSONObject的C = country_list.getJSONObject(I)
//创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
//将每个子节点的HashMap键=>值
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(说明)的toString()。
/ *的JSONObject JS =新的JSONObject();
js.getString(说明);
DESC = js.toString(); * /
//的System.out.println(jsjsj+ DESC); data.add(地图); }
}赶上(JSONException E){
e.printStackTrace();
}
}其他{
Log.e(的ServiceHandler,无法从URL得到任何数据);
} 返回的数据;
}
保护无效onPostExecute(ArrayList的<&HashMap的LT;字符串,字符串>>的结果){
super.onPostExecute(结果);
pDialog.dismiss();
如果(ALIST == NULL)
{
ALIST =新的ArrayList<&HashMap的LT;字符串,字符串>>();
aList.addAll(结果);
适配器=新CustomAdapterBusinessCard(getBaseContext(),结果);
setListAdapter(适配器);
}
其他
{
aList.addAll(结果);
adapter.notifyDataSetChanged();
}
}
}
列表视图
< RelativeLayout的
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:背景=@机器人:彩色/白
> < ListView控件
机器人:layout_height =WRAP_CONTENT
机器人:layout_width =WRAP_CONTENT
机器人:ID =@机器人:ID /列表
机器人:dividerHeight =1DP >< /&的ListView GT;
< / RelativeLayout的>
列表项
<的LinearLayout
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直>
< ImageView的
机器人:layout_height =WRAP_CONTENT
机器人:layout_width =WRAP_CONTENT
机器人:ID =@ + ID / imgvwbusinesscard
/>
<按钮
机器人:layout_height =WRAP_CONTENT
机器人:layout_width =WRAP_CONTENT
机器人:文字=下载
机器人:ID =@ + ID / dwnldbutton /> < / LinearLayout中>
我做到了使用的AsyncTask从URL中下载图片。
类DownloadImageAsyncTask扩展的AsyncTask<太虚,太虚,太虚>
{ @覆盖
保护无效doInBackground(无效... PARAMS)
{
// TODO自动生成方法存根
downloadImages();
返回null;
} @覆盖
保护无效onPostExecute(虚空结果)
{
// TODO自动生成方法存根
super.onPostExecute(结果); } }
这是下载图像功能,你可以从很多网站获得的参考。
私人无效downloadImages()
{ 网址图片网址; //您的网址从图像被下载
字符串域;
尝试
{
图片网址=新的URL(你的URL); HttpURLConnection类URLConnection的;
尝试
{
URLConnection的=(HttpURLConnection类)imageUrl.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(真);
urlConnection.connect();
字符串路径= getExternalCacheDir()+文件分割符+ getResources()的getString(R.string.app_name)。
文件f =新的文件(路径);
如果(!f.exists())
{
f.mkdirs();
}
档案文件=新的文件(FImageName.png); //在这里你可以保存图像用名和扩展名
如果(!file.exists())
{
file.createNewFile();
}
FileOutputStream中fileOutput =新的FileOutputStream(文件);
为InputStream的InputStream = urlConnection.getInputStream();
字节[]缓冲区=新的字节[1024];
INT BufferLength中= 0; //用于存储的临时尺寸
//缓冲区
而(量(bufferLength = inputStream.read(缓冲液))大于0)
{
fileOutput.write(缓冲液,0,BufferLength中);
}
fileOutput.close();
}
赶上(IOException异常E)
{
e.printStackTrace();
} }
赶上(MalformedURLException的E)
{
e.printStackTrace();
} }
然后在您的适配器类,你可以这样设置图像:
holder.propic.setImageDrawable(Drawable.createFromPath(getExternalCacheDir()+文件分割符
+ getResources()的getString(R.string.app_name)+文件分割符+ImageName.png)); //其中保存图像确切路径。
希望它可以帮助你。
I am getting response from server and in my response i am getting image,the view of that response is in listview,now what i want is below image i have one button for download image,and I want to download that image and store it in gallery..below is my code and response..
JSON Response..
[
{
"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();
}
}
} MyActivity
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();
}
}
}
listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<ListView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@android:id/list"
android:dividerHeight="1dp"
></ListView>
</RelativeLayout>
listitem
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imgvwbusinesscard"
/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Download"
android:id="@+id/dwnldbutton"
/>
</LinearLayout>
I did it by using AsyncTask to download image from a 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);
}
}
This is the download image function which you can get reference from many sites.
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();
}
}
Then in your Adapter class you can set the image by doing this:
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.
Hope it might help you.
这篇关于下载图像并保存在画廊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!