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

网上很多是访问网页上的图片,比如“http://www.nowamagic.net/librarys/images/random/rand_11.jpg”,话说我又不会把图片放到网页上

本文是显示存储在服务器的图片,比如“F://upload//2.jpg”

服务器端:

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 {

		// response.setContentType("text/html");
		// PrintWriter out = response.getWriter();
		// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		// out.println("<HTML>");
		// out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		// out.println("  <BODY>");
		// out.print("    This is ");
		// out.print(this.getClass());
		// out.println(", using the GET method");
		// out.println("  </BODY>");
		// out.println("</HTML>");
		// out.flush();
		// out.close();
		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();
		// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		// out.println("<HTML>");
		// out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		// out.println("  <BODY>");
		// out.print("    This is ");
		// out.print(this.getClass());
		// out.println(", using the POST method");
		// out.println("  </BODY>");
		// out.println("</HTML>");
		out.print(GetImageStr());// /输出文件的字符串
		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() {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
										// String imgFile =
										// "d://test.jpg";//待处理的图片

		String imgFile = "F://upload//2.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
}
手机端:

package com.example.displaynetworkimage_1;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

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 ImageView imageView1;
	private Button button1;
	private Bitmap bitmapImage;
	//String responseMessage ;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView1 = (ImageView) findViewById(R.id.imageView1);
		button1 = (Button) findViewById(R.id.button1);
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				Log.i("button1", "button1");
				fun_HttpPost();
			}
		});
           
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO 自动生成的方法存根
				//super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					//String bitmapString = (String)msg.obj;
					//imageView1.setImageBitmap(GenerateImage(bitmapString));
					imageView1.setImageBitmap((Bitmap)msg.obj);///回收msg
					break;
				default:
					break;
				}
			}//handleMessage
		};///handler=new Handler()
	}// ///onCreate

	public void fun_HttpPost() {
		new Thread(new Runnable() {在子线程中传递msg,主线程中接收msg;;要是用fun_HttpPost()的返回值会失败
			@Override
			public void run() {
				// TODO 自动生成的方法存根
				String urlStr = "http://192.168.0.122:8080/download/servlet/download";
				HttpPost request = new HttpPost(urlStr);
				try {
					HttpClient client = getHttpClient();
					// 执行请求返回相应
					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=0;
                         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;
	}

	// 初始化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()

}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="54dp"
        android:layout_marginTop="114dp"
        android:layout_toRightOf="@+id/textView1"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:text="Button" />

</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.displaynetworkimage_1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="16" />
        <!-- 使用网络功能所需权限 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- SDK离线地图和cache功能需要读写外部存储器 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        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>


手机和电脑连接同一个wifi


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二十六画生的博客

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值