listView显示保存在服务器的图片,不是网页上的图片

查了很多文档终于搞明白了,SimpleAdapter中的from参数是hashmap,但value不一定非要是int 型的id才行,是bitmap也行,只不过后面再处理一下即可,移动端::手机和电脑连接同一个wifi

package com.example.listview_8;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟
	private static final int SO_TIMEOUT = 10 * 60 * 1000; // 设置请求超时时间10秒钟
	private static final int LOGIN_OK = 1;

    private Handler handler ;
	private ListView lv1;

	private int  COUNT=5;//////COUNT=10时图片显示会乱序,有待改进
	private Bitmap[] imagesId=new Bitmap[COUNT];
//	private	String[] names={"短毛猫"};
//	private  String[] mark={"可爱"};
//	private	String[] names={"短毛猫1","猴子2","兔子3","老鼠4","斑马5","短毛猫6","猴子7","兔子8","老鼠9","斑马10"};
//	private  String[] mark={"可爱1","顽皮2","温顺3","伶俐4","强壮5","可爱6","顽皮7","温顺8","伶俐9","强壮10"};
	private	String[] names={"短毛猫1","猴子1","兔子1","老鼠1","斑马1"};
	private  String[] mark={"可爱1","顽皮1","温顺1","伶俐1","强壮1"};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lv1 = (ListView) findViewById(R.id.listView1);

		final List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();

		for(int i=1;i<=COUNT;i++){
			fun_HttpPost(i);
		}

		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO 自动生成的方法存根
				///super.handleMessage(msg);

				if((Bitmap)msg.obj!=null){
					Log.i("==========================Bitmap)msg.obj==null===================", "Bitmap)msg.obj==null");
				}
				int num=msg.what-1;
				imagesId[num]=(Bitmap)msg.obj;
//				for(int i=msg.what-1;i<names.length;i++){
//					Map<String,Object> listItem = new HashMap<String,Object>();
//					listItem.put("face", imagesId[i]);
//					listItem.put("name", names[i]);
//					listItem.put("mark", mark[i]);
//					listItems.add(listItem);
//				}
				Map<String,Object> listItem = new HashMap<String,Object>();
				listItem.put("face", imagesId[num]);
				listItem.put("name", names[num]);
				listItem.put("mark", mark[num]);
				listItems.add(listItem);
				SimpleAdapter simleAdapter = new SimpleAdapter(MainActivity.this, listItems,
						R.layout.custom_list	,new String[]{"face","name","mark"},
						new int[]{R.id.face,R.id.name,R.id.mark});

					simleAdapter.setViewBinder(new ViewBinder() {

						public boolean setViewValue(View view, Object data,
								String textRepresentation) {
							// 判断是否为我们要处理的对象
							if (view instanceof ImageView && data instanceof Bitmap) {
								ImageView iv = (ImageView) view;

								iv.setImageBitmap((Bitmap) data);
								return true;
							} else
								return false;
						}
					});
					lv1.setAdapter(simleAdapter);
			}////handleMessage

		};////handler = new Handler()
		lv1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 自动生成的方法存根
				Toast.makeText(MainActivity.this, "点击的是第"+position+"个条目", Toast.LENGTH_SHORT).show();
			}
		});

//		Bitmap catBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.cat);
//		Bitmap monkeyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.monkey);
//		Bitmap rabbitBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.rabbit);
//		Bitmap ratBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.rat);
//		Bitmap	imagesId[]={catBitmap,monkeyBitmap,rabbitBitmap,ratBitmap};

	}///onCreate

	public void fun_HttpPost(final int i) {// //生成faceBitmap[]
		new Thread(new Runnable() {// //在子线程中传递msg,主线程中接收msg;;要是用fun_HttpPost()的返回值会失败
					@Override
					public void run() {
						// TODO 自动生成的方法存根
						String urlStr = "http://192.168.0.101:8080/download/servlet/download";
						HttpPost request = new HttpPost(urlStr);
						// 如果传递参数多的话,可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						// 设置要下载的头像名称
						params.add(new BasicNameValuePair("picN", String
								.valueOf(i)));
						// params.add(new BasicNameValuePair("pic2","2"));
						// params.add(new BasicNameValuePair("pic3","3"));
						// params.add(new BasicNameValuePair("password",
						// passwordString));
						// params.add(new BasicNameValuePair("nickname",
						// nicknameString));

						try {
							HttpClient client = getHttpClient();
							request.setEntity(new UrlEncodedFormEntity(params,
									HTTP.UTF_8));
							// 执行请求返回相应
							HttpResponse response = client.execute(request);
							// 判断是否请求成功
							if (response.getStatusLine().getStatusCode() == 200) {
								// 获得响应信息
								String responseMessage = EntityUtils
										.toString(response.getEntity());
								Log.i("responseMessage", responseMessage
										+ ",长度:" + responseMessage.length());
								Bitmap bitmap = GenerateImage(responseMessage);// //生成Bitmap

								Message msg = new Message();
								msg.what = i;
								//
								Log.i("------------------- msg.what=i---------------",
										String.valueOf(i - 1));
								//
								msg.obj = bitmap;// //传递msg
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}// //run()
				}).start();

	}// /fun_register()

	// base64字符串转化成图片
	public static Bitmap GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
		{
			Log.i("imgStr == null", "imgStr == null");
			return setNullBitmapImage();
		}
		Decoder.BASE64Decoder decoder = new Decoder.BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			InputStream ins = new ByteArrayInputStream(b);
			Bitmap bitmap = new BitmapFactory().decodeStream(ins);
			return bitmap;
		} catch (Exception e) {
			Log.i("imgStr == null,catch (Exception e)",
					"imgStr == null,catch (Exception e)");
			return setNullBitmapImage();
		}
	}// /GenerateImage

	private static Bitmap setNullBitmapImage() {

		String filePath = "/sdcard/1spray/11.jpg";
		File file = new File(filePath);
		Bitmap bitmap = null;
		try {
			InputStream is = new FileInputStream(file);
			bitmap = new BitmapFactory().decodeStream(is);
			Log.i("setNullBitmapImage()", "setNullBitmapImage()");
			// /imageView1.setImageBitmap(bitmap);
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return bitmap;
	}///setNullBitmapImage

	// 初始化HttpClient,并设置超时
	public HttpClient getHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(httpParams);
		return client;
	}// /public HttpClient getHttpClient()
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/face"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="57dp"
        android:layout_marginTop="20dp"
        android:layout_toRightOf="@+id/face"
        android:paddingLeft="20dp"
        android:text="TextView"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/mark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/name"
        android:layout_below="@+id/name"
        android:layout_marginTop="10dp"
         android:textSize="15sp"
        android:text="mark"
  />

</RelativeLayout>
</pre><pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.listview_8"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</pre><pre name="code" class="html">

服务器端::

package com;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

public class download extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public download() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 *
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to
	 * post.
	 *
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		// request.setCharacterEncoding("utf-8");////这句至关重要,不然中文的文件名称显示乱码
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String picN = request.getParameter("picN");
		//String pic2 = request.getParameter("pic2");
//		String password = request.getParameter("password");
//		String nickname = request.getParameter("nickname");
//		String faceImageString = request.getParameter("faceImage");

		out.print(GetImageStr(picN));// /输出文件的字符串

		out.flush();
		out.close();

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public static String GetImageStr(String picName) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
										// String imgFile =
										// "d://test.jpg";//待处理的图片

		String imgFile = "F://upload//"+picName+".jpg";// //可以
		// String imgFile = "F://upload//软工大作业.ppt";// //可以
		// String imgFile="F://upload//爱的勇气.mp3";//可以
		// String imgFile="F://upload//upload.rar";//可以
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	} // /GetImageStr
}

时间: 2024-10-23 18:59:43

listView显示保存在服务器的图片,不是网页上的图片的相关文章

psd图片不能在网页上显示

原因:web上不支持psd图片,web支持JPG,PNG等. 解决:打开ps点击文件--储存为web所用格式(选择转换成哪种格式). 原文地址:https://www.cnblogs.com/hq12345/p/9378352.html

c++ 实现https网页上的图片爬取

一.主要的原理 我们通过发送一个http请求,获得目标网页的html源代码,然后通过正则表达式获取到图片的URL,把该网页的所有的图片都保存到一个文件夹,这就是整个软件的流程. 二.具体的实践 现在很多的网站都是https协议但是有一部分还是http协议,其实https就是http协议的安全版本,相当于http+ssl,SSL是介于HTTP应用层和TCP传输层,和HTTP相比HTTPS发送数据需要SSL加密,然后发送.所以说我们想通过https协议发送数据给服务器,需要经历一下这几个步骤: 首先

Android获取网页上的图片的代码

public Bitmap getWebBitmap(String imgUrl) { Bitmap bitmap =null; try { InputStream inputStream = null; URL url; url = new URL(imgUrl); if (url != null) { // 打开连接 HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURL

js或者jquery直接下载网页上的图片代码

1.jquery方式 使用jquery直接下载图片 function downloadImage(src) { var a = $("<a></a>").attr("href", src).attr("download", "img.png").appendTo("body"); a[0].click(); a.remove(); } 2,兼容模式IE下 IE下使用canvas 然后

用瀑布流的方式在网页上插入图片

当我们的网页需要插入很多图片的时候,为了美观,我们可以选择用瀑布流的方法插入图片 首先我们在body里面放入我们需要展示的图片 <div id="box"> <div class="dinwei"> <div class="pic"> <img src="image/1.jpg"> </div> </div> <div class="din

Python3.x爬虫教程:爬网页、爬图片、自动登录

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文将使用Python3.4爬网页.爬图片.自动登录.并对HTTP协议做了一个简单的介绍.在进行爬虫之前,先简单来进行一个HTTP协议的讲解,这样下面再来进行爬虫就是理解更加清楚. 一.HTTP协议 HTTP是Hyper Text Transfer Protocol(超文本传输协议)的缩写.它的发展是万维网协会(World Wide Web Consortium)和Internet工作

js实现图片预览以及上传

HTML 代码: <input  type="file" id="fileid" onchange="filesize(this)" runat="server" size="80" Width="200px" Height="25px"/>  <input  type="hidden" id="hidden_s&quo

关于网页上图片无缝滚动的一些思路

从现在的一些常见网站上,无缝滚动的例子用得非常普遍,可以说很常见,也比较实用,下面我们就来简单看看,具体的一些想法怎么实现的: 先简单来看一下原理: 首先我们看到网页上一组图片不停滚动,一次循环之后又从第一张开始,其实简单的思路是:我们设置两组图片,当第一组图片滚动到结尾时,对应的第一组图片又瞬间拉回到起始位置. 当图片向另外一个方向滚动时,当后面一组图片滚动到结尾时:也是瞬间拉回到开头. 下面我们简单来看一下代码: <!DOCTYPE html><html><head>

Android在ListView显示图片(重复错乱闪烁问题)

1.原因分析 ListView item缓存机制: 为了使得性能更优,ListView会缓存行item(某行对应的View). ListView通过adapter的getView函数获得每行的item. 滑动过程中 a. 如果某行item已经滑出屏幕,若该item不在缓存内,则put进缓存,否则更新缓存: b. 获取滑入屏幕的行item之前会先判断缓存中是否有可用的item,如果有,做为convertView参数传递给adapter的getView. 这样,如下的getView写法就可以充分利用