时间:2021-05-20
本文实例讲述了Android实现拍照上传功能的方法。分享给大家供大家参考,具体如下:
1、LoginWindow.java --登录窗口
package com.hemi.rhet;import com.hemi.rhet.R;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;public class LoginWindow extends Activity { @Override public void onCreate(Bundle savedInstanceState) { System.out.println("enter LoginWindow.onCreate()!"); super.onCreate(savedInstanceState); setContentView(R.layout.login_window); mUserName = (EditText)findViewById(R.id.username); mUserPasswd = (EditText)findViewById(R.id.userpasswd); cbx_cmwap = (CheckBox) findViewById(R.id.cbx_cmwap); loginButton = (Button) findViewById(R.id.login_button); exitButton = (Button) findViewById(R.id.exit_button); loginBtnListener = new View.OnClickListener() { public void onClick(View view) { LoginWindow.isCmwap = cbx_cmwap.isChecked(); if (view == loginButton) { launchFetion(); } else if(view == exitButton) { finish(); } } }; loginButton.setOnClickListener(loginBtnListener); exitButton.setOnClickListener(loginBtnListener); } private void launchFetion() { Intent i = new Intent(this, FuncSelector.class); i.putExtra(KEY_LOGIN_NAME, mUserName.getText().toString()); i.putExtra(KEY_LOGIN_PASSWD, mUserPasswd.getText().toString()); i.putExtra(KEY_LOGIN_TYPE, cbx_cmwap.isChecked()); startActivity(i); } @Override public boolean onKeyDown(int keyCode, KeyEvent msg) {// System.out.println("enter onKeyDown() in LoginWindow!");//// if (null != loginBtnListener) {// View aview = getCurrentFocus();// loginBtnListener.onClick(aview);// } return false; } private Button loginButton, exitButton; private EditText mUserName; private EditText mUserPasswd; private CheckBox cbx_cmwap; private OnClickListener loginBtnListener; public static final String KEY_LOGIN_NAME = "login_name"; public static final String KEY_LOGIN_PASSWD = "login_passwd"; public static final String KEY_LOGIN_TYPE = "login_type"; public static boolean isCmwap = false;}2. FuncSelector.java -- 功能模块选择窗口
package com.hemi.rhet;import java.util.ArrayList;import java.util.HashMap;import com.hemi.rhet.R;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.GridView;import android.widget.SimpleAdapter;import android.widget.AdapterView.OnItemClickListener;public class FuncSelector extends Activity { @Override public void onCreate(Bundle savedInstanceState) { Log.i("info", "enter LoginWindow.onCreate()!"); super.onCreate(savedInstanceState); setContentView(R.layout.func_selector); initFuncGrids(); } private void initFuncGrids() { GridView funcSeleView = (GridView) findViewById(R.id.func_selector); // 生成动态数组,并且转入数据 ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("ItemImage", R.drawable.photo_upload); // 添加图像资源的ID map.put("ItemText", getString(R.string.photo_upload)); // 按序号做ItemText lstImageItem.add(map); map = new HashMap<String, Object>(); map.put("ItemImage", R.drawable.icon); map.put("ItemText", getString(R.string.sys_config)); lstImageItem.add(map); for (int i = 1; i <= 10; i++) { map = new HashMap<String, Object>(); map.put("ItemImage", R.drawable.icon); // 添加图像资源的ID map.put("ItemText", "NO." + String.valueOf(i)); // 按序号做ItemText lstImageItem.add(map); } // 生成适配器的ImageItem <====> 动态数组的元素,两者一一对应 SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释 lstImageItem,// 数据来源 R.layout.night_item,// night_item的XML实现 // 动态数组与ImageItem对应的子项 new String[] { "ItemImage", "ItemText" }, // ImageItem的XML文件里面的一个ImageView,两个TextView ID new int[] {R.id.ItemImage,R.id.ItemText}); //null); // 添加并且显示 funcSeleView.setAdapter(saImageItems); //saImageItems.notifyDataSetChanged(); // 添加消息处理 funcSeleView.setOnItemClickListener(new ItemClickListener()); } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EXIT_ID,0, R.string.back_button); return true; } //@Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean result = true; switch(item.getItemId()) { case EXIT_ID: this.finish(); break; default: result = super.onMenuItemSelected(featureId, item); break; } return result; } // 当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件 class ItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0,// The AdapterView where the // click happened View arg1,// The view within the AdapterView that was clicked int arg2,// The position of the view in the adapter long arg3// The row id of the item that was clicked ) { // 在本例中arg2=arg3 HashMap<String, Object> item = (HashMap<String, Object>) arg0 .getItemAtPosition(arg2); String tmpStr = (String) item.get("ItemText"); //item.put("ItemText", tmpStr + tmpStr.substring(tmpStr.length() - 1)); // 显示所选Item的ItemText // setTitle((String)item.get("ItemText")); Log.i("info", (String) item.get("ItemText")); ((SimpleAdapter) arg0.getAdapter()).notifyDataSetChanged(); Intent i; switch (arg2) { case 0: i = new Intent(); i.setClass(FuncSelector.this, PhotoUpload.class); startActivity(i); break; case 1: i = new Intent(); i.setClass(FuncSelector.this, ConfigWindow.class); startActivity(i); break; default: break; } } } private static final int TAKE_PHOTO_ID = Menu.FIRST; private static final int UPLOAD_PHOTO_ID = Menu.FIRST + 1; private static final int EXIT_ID = Menu.FIRST + 3;}//FuncSelector3. PhotoUpload.java -- 照片上传模块
package com.hemi.rhet;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import org.apache.http.Header;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.FileEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import com.hemi.rhet.R;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.GridView;import android.widget.ImageView;import android.widget.SimpleAdapter;import android.widget.Toast;import android.widget.AdapterView.OnItemClickListener;public class PhotoUpload extends Activity { @Override public void onCreate(Bundle savedInstanceState) { Log.i("info", "enter LoginWindow.onCreate()!"); super.onCreate(savedInstanceState); setContentView(R.layout.func_selector); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (TAKE_PHOTO_ID == requestCode) { if (resultCode != RESULT_OK) return; Bundle extras = data.getExtras(); try { Bitmap photoCaptured = (Bitmap) extras.get("data"); ImageView img = new ImageView(this); img.setImageBitmap(photoCaptured); setContentView(img); //store to sd card ByteArrayOutputStream baos = new ByteArrayOutputStream(); photoCaptured.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] photoBytes = baos.toByteArray(); File aFile = new File(getDatedFName(SD_CARD_TEMP_DIR)); photoPath = aFile.getAbsolutePath(); boolean b; if (aFile.exists()) b = aFile.delete(); //f.mkdirs(); aFile.createNewFile(); //need add permission to manifest FileOutputStream fos = new FileOutputStream(aFile); fos.write(photoBytes); fos.close(); Log.d("info", "onPictureTaken - wrote bytes: " + photoBytes.length); Uri capturedImage = Uri .parse(android.provider.MediaStore.Images.Media .insertImage(getContentResolver(), aFile .getAbsolutePath(), null, null)); Log.i("camera", "Selected image: " + capturedImage.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (UPLOAD_PHOTO_ID == requestCode) { } } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, TAKE_PHOTO_ID,0, R.string.take_photo); menu.add(0, UPLOAD_PHOTO_ID,0, R.string.upload_photo); menu.add(0, BACK_ID,0, R.string.back_button); return true; } //@Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean result = true; switch(item.getItemId()) { case TAKE_PHOTO_ID: Log.i("info", "ready to take photos!"); Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(i, TAKE_PHOTO_ID); result = true; break; case UPLOAD_PHOTO_ID: uploadFile2Svr(); break; case BACK_ID: this.finish(); break; default: result = super.onMenuItemSelected(featureId, item); break; } return result; } public void uploadFile2Svr() { HttpClient httpclient = new DefaultHttpClient(); String urlStr = new StringBuffer().append(HTTP_PROTOCOL) .append(ConfigWindow.getServerIp()) .append(':') .append(ConfigWindow.getServerPort()) .append(FILE_UPLOADER_URL) .toString(); HttpPost httppost = new HttpPost(urlStr); String uploadMsg = "上传 照片失败!"; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // Your DATA nameValuePairs.add(new BasicNameValuePair("filename", ("IMAGE.jpg")) );// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));// nameValuePairs.add(new BasicNameValuePair("userid", "123"));// nameValuePairs.add(new BasicNameValuePair("attach_type", "1"));// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); File aFile = new File(photoPath); Log.i("info -- photoPath: ", photoPath); FileEntity fileEty = new FileEntity(aFile, "binary/octet-stream"); httppost.setEntity(fileEty); httppost.addHeader("filename", aFile.getName()); HttpResponse response; response = httpclient.execute(httppost); //Log.i("info -- response: ", response.getStatusLine().getReasonPhrase()); Header[] headers = response.getAllHeaders(); headers = response.getHeaders("resultcode"); if (headers[0].getValue().equals("0")) { uploadMsg = "上传照片成功!"; } } catch (UnsupportedEncodingException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("exception", e.toString()); } catch (ClientProtocolException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("exception", e.toString()); } catch (IOException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("exception", e.toString()); } finally { Toast.makeText(PhotoUpload.this, uploadMsg, Toast.LENGTH_LONG).show(); httpclient.getConnectionManager().shutdown(); } } public void uploadFile2Svr2() { BufferedReader in = null; HttpClient httpclient = new DefaultHttpClient(); String urlStr = new StringBuffer().append(HTTP_PROTOCOL) .append(ConfigWindow.getServerIp()) .append(ConfigWindow.getServerPort()) .append(FILE_UPLOADER_URL) .toString(); URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "/r/n"; String twoHyphens = "--"; String boundary = "*****"; int maxBufferSize = 16 * 1024; try {// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();// // Your DATA// nameValuePairs.add(new BasicNameValuePair("filename", getDatedFName("IMAGE.jpg")) );// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));// nameValuePairs.add(new BasicNameValuePair("userid", "123"));// nameValuePairs.add(new BasicNameValuePair("attach_type", "1")); //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(120000); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", //"multipart/form-data;boundary=" + boundary); "application/x-.hemi.rhet.servlet.UploadFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Upload</servlet-name> <url-pattern>/system/fileUpload</url-pattern> </servlet-mapping></web-app>更多关于Android相关内容感兴趣的读者可查看本站专题:《Android拍照与图片处理技巧总结》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
最近做的APP项目涉及到手机拍照上传图片,因为手机拍照的图片通常都比较大,所以上传的时候就会很慢。为此,需要对图片进行压缩处理来优化上传功能。以下是具体实现:/
不废话了,具体请看下文代码示例讲解。form.phpUploadImageupload.phpUploadImage以上内容就是给大家讲解的php上传功能集后缀
最近在做一个移动端HTML5的应用,使用到了上传功能,起初使用传统的上传方式上传手机拍照的照片,由于手机拍照出来的照片一般都是好几MB,所以上传速度是非常慢的。
最近在做一个移动端HTML5的应用,使用到了上传功能,起初使用传统的上传方式上传手机拍照的照片,由于手机拍照出来的照片一般都是好几MB,所以上传速度是非常慢的。
前言最近在工作的过程中,遇到不同Android版本下URI采用不同方式来获取文件路径的问题。因为需求的原因,要求拍照上传或者从相册中选择图片上传,而且图片是需要