// 获得url // 构造源参数 public static String GetUrl(List<NameValuePair> myParameter) { // 初始化参数 List<NameValuePair> jsonvalue = initParameter(myParameter); // 获得字符串 String UrlPam = getStrUrlPam(jsonvalue); // 签名字符串 String HamacSha1 = HMACSHA1.hmac_sha1(MySetting.Secret + "&",URLEncoder.encode("&" + UrlPam)).trim(); return MySetting.PostImageUrl + "?" + UrlPam + "&s=" + HamacSha1; } @SuppressLint("NewApi") public static String newUploadFile(String path, String fileName, List<NameValuePair> params) { String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; try { URL url = new URL(GetUrl(params)); HttpURLConnection con = (HttpURLConnection) url.openConnection(); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"filedata\";filename=\"" + fileName + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(path); /* 设置每次写入1024bytes */ int bufferSize = 1024*10; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fStream.read(buffer)) != -1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } ds.close(); return b.toString(); }catch (Exception e) { } return null; } @SuppressLint("NewApi") public static String uploadFile(String path, String fileName, List<NameValuePair> params) { String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; StringBuffer b = new StringBuffer(); try { URL url = new URL(GetUrl(params)); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); /* Read from the connection. Default is true. */ con.setDoInput(true); /* Post cannot use caches */ con.setUseCaches(false); /* Set the post method. Default is GET */ con.setRequestMethod("POST"); /* 设置请求属性 */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 设置StrictMode 否则HTTPURLConnection连接失败,因为这是在主进程中进行网络连接 */ /*StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build());*/ con.connect(); /* 设置DataOutputStream,getOutputStream中默认调用connect() */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); // output // to // the // connection ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"filedata\";filename=\"" + fileName + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(path); /* 设置每次写入8192bytes */ // int bufferSize = 8192; byte[] buffer = new byte[8192]; // 8k // int length = -1; // /* 从文件读取数据至缓冲区 */ // while ((length = fStream.read(buffer)) != -1) { // /* 将资料写入DataOutputStream中 */ // ds.write(buffer, 0, length); // } // ds.writeBytes(end); // ds.writeBytes(twoHyphens + boundary + twoHyphens + end); // /* 关闭流,写入的东西自动生成Http正文 */ // fStream.close(); // /* 关闭DataOutputStream */ // ds.close(); // /* 从返回的输入流读取响应信息 */ // InputStream is = con.getInputStream(); // input from the connection // // 正式建立HTTP连接 // int ch; // while ((ch = is.read()) != -1) { // b.append((char) ch); // } int count = 0; // 读取文件 int sum = 0; while ((count = fStream.read(buffer)) != -1) { ds.write(buffer, 0, count); sum += count; } System.out.println(sum); fStream.close(); ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); ds.flush(); InputStream is = con.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String result = br.readLine(); System.out.println(result); ds.close(); is.close(); //httpURLConnection.disconnect(); return result; /* 显示网页响应内容 */ // Toast.makeText(MainActivity.this, b.toString().trim(), // Toast.LENGTH_SHORT).show();//Post成功 //System.out.println(b.toString().trim()); } catch (Exception e) { /* 显示异常信息 */ // Toast.makeText(MainActivity.this, "Fail:" + e, // Toast.LENGTH_SHORT).show();//Post失败 System.out.println("Fail:" + e); } return b.toString(); }
Activity
package com.setbuy.activity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; import com.setbuy.dao.RegisterDao; import com.setbuy.dao.SetParamDao; import com.setbuy.utils.ImageUtils; import com.setbuy.utils.IsHtmlOrProto; import com.setbuy.utils.MessgeUtil; import com.setbuy.utils.NetWork; import com.setbuy.utils.PermissionUtils; import com.setbuy.utils.T; import com.setbuy.utils.UserUtil; import come.setbuy.view.CustomProgressDialog; import android.app.Activity; import android.app.Dialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.provider.MediaStore.Images.ImageColumns; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.Toast; /** * 门头照 * */ public class RegisterActivityThree extends Activity{ private ImageView iv_next,imgview; private ImageView iv_photo; private Dialog dialog; private Uri uri; private String picPath = null; private String bitnum, imgnum; private static final int REQUESTCODE = 3333; private CustomProgressDialog pd; private Map<String, String> imgInfo; private String iurla = ""; private Bitmap bitmap,bitmap2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.registerthree); init();//初始化 } private void init() { iv_next = (ImageView) findViewById(R.id.iv_next); iv_next.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(RegisterActivityThree.this,RegisterActivityFour.class); startActivity(intent); } }); iv_photo = (ImageView) findViewById(R.id.iv_photo); iv_photo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { PermissionUtils.verifyStoragePermissions(RegisterActivityThree.this); if (isCameraUseable() == true) { PackageManager pm = getPackageManager(); boolean Iscamera = (PackageManager.PERMISSION_GRANTED == pm .checkPermission("android.permission.CAMERA", "com.setbuy.activity")); if (Iscamera) { newShowDialog(iv_photo,"4");//符合条件 } else { Toast.makeText(RegisterActivityThree.this, "请开启照相机权限!", Toast.LENGTH_LONG).show(); } }else { Toast.makeText(RegisterActivityThree.this, "请开启照相机权限!", Toast.LENGTH_LONG).show(); } } }); } //调起自定义框 private void newShowDialog(ImageView gv, String num) { imgview = gv; bitnum = num; View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null); dialog = new Dialog(this, R.style.transparentFrameWindowStyle); dialog.setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; dialog.onWindowAttributesChanged(wl); dialog.setCanceledOnTouchOutside(true); dialog.show(); } public void on_click(View vr) { switch (vr.getId()) { case R.id.openCamera: dialog.dismiss(); ImageUtils.openLocalImage(RegisterActivityThree.this); break; case R.id.openPhones: dialog.dismiss(); ImageUtils.openCameraImage(RegisterActivityThree.this); break; case R.id.cancel: dialog.cancel(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CANCELED) { return; } switch (requestCode) { // 拍照获取图片 case ImageUtils.GET_IMAGE_BY_CAMERA: if (ImageUtils.imageUriFromCamera != null) { ImageUtils.cropImage(this, ImageUtils.imageUriFromCamera); break; } break; // 手机相册获取图片 case ImageUtils.GET_IMAGE_FROM_PHONE: if (data != null && data.getData() != null) { ImageUtils.cropImage(this, data.getData()); } break; // 裁剪图片后结果 case ImageUtils.CROP_IMAGE: if (ImageUtils.cropImageUri != null) { uri = ImageUtils.cropImageUri; picPath = getRealFilePath(RegisterActivityThree.this, uri); imgnum = bitnum; if (imgnum == "4") { dodtimp("dd.jpg"); } } break; case REQUESTCODE: break; default: break; } } private void dodtimp(final String fname) { // 判断网络 if (!NetWork.isNetWork(RegisterActivityThree.this)) { return; } if (pd == null) { pd = new CustomProgressDialog(this,"上传中请稍等...",R.anim.frame_dialog1); pd.show(); } new Thread(new Runnable() { @Override public void run() { Message msg = userHandlerr.obtainMessage(); msg.what = 1; imgInfo = RegisterDao.geturl(picPath, fname, bitnum); userHandlerr.sendMessage(msg); } }).start(); } Handler userHandlerr = new Handler() { @SuppressWarnings("deprecation") public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: break; case 1: iurla = SetParamDao.mapGetByKey(imgInfo,"url"); bitmap = getBitmapFromUri(uri, RegisterActivityThree.this); bitmap2 = comp(bitmap); imgview.setImageBitmap(bitmap2); if(imgInfo!=null&&"0".equals(imgInfo.get(T.OtherConst.Ret))){ if (null != pd && pd.isShowing()) { pd.dismiss(); pd = null; } }else{ dodtimp("aa.jpg"); } break; default: break; } } }; public static String getRealFilePath(final Context context, final Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[] { ImageColumns.DATA }, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; } public static Bitmap getBitmapFromUri(Uri uri, Context mContext) { try { // 读取uri所在的图片 Bitmap bitmap = MediaStore.Images.Media.getBitmap( mContext.getContentResolver(), uri); return bitmap; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 压缩图片显示 */ private Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; float hh = 100f;// 这里设置高度为100f float ww = 100f;// 这里设置宽度为100f int be = 1;// be=1表示不缩放 if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 设置缩放比例 // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩 } private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10;// 每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 return bitmap; } public static boolean isCameraUseable() { boolean canUse = true; Camera mCamera = null; try { mCamera = Camera.open(); // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null Camera.Parameters mParameters = mCamera.getParameters(); mCamera.setParameters(mParameters); } catch (Exception e) { canUse = false; } if (mCamera != null) { mCamera.release(); } return canUse; } }
布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:orientation="vertical" > <RelativeLayout android:id="@+id/rl_registerone" android:layout_width="match_parent" android:layout_height="45dip"> <ImageView android:id="@+id/registerone_btnBack" android:layout_width="30dp" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:gravity="center_vertical" android:padding="10dp" android:layout_marginLeft="5dp" android:src="@drawable/row_left" /> <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:gravity="center" android:text="门头照片" android:textSize="19sp" /> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="0.2dp" android:background="#E5E5E5" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textSize="13dp" android:textColor="#646464" android:gravity="center" android:text="请在门店位置拍摄门头照,以免影响后续下单收货"/> <RelativeLayout android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="180dp"> <ImageView android:src="@drawable/register_shop" android:layout_centerInParent="true" android:layout_width="300dp" android:layout_height="200dp"/> <ImageView android:id="@+id/iv_photo" android:layout_centerInParent="true" android:layout_width="100dp" android:scaleType="fitXY" android:layout_height="100dp" android:src="@drawable/register_image"/> </RelativeLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:textSize="13dp" android:textColor="#aaaaaa" android:gravity="center" android:text="*请保证门店名称拍摄清晰,例:"/> <ImageView android:layout_marginTop="15dp" android:layout_width="250dp" android:layout_gravity="center" android:layout_height="wrap_content" android:src="@drawable/register_shop_two"/> <RelativeLayout android:layout_width="wrap_content" android:layout_marginTop="13dp" android:layout_height="wrap_content"> <ImageView android:id="@+id/iv_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="17dp" android:paddingRight="17dp" android:src="@drawable/nextbutton"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下一步" android:textSize="16dp" android:textColor="@color/white" android:layout_centerInParent="true"/> </RelativeLayout> </LinearLayout>
辅助类
public static Map<String,String> geturl(String path,String name,String context) { List<NameValuePair> listNamePair = new ArrayList<NameValuePair>(); listNamePair.add(new BasicNameValuePair(T.OtherConst.Api, "file/upload")); listNamePair.add(new BasicNameValuePair(T.Users.Filedata, "filedata")); listNamePair.add(new BasicNameValuePair(T.Users.Context, context)); String ttString=SetParamDao.newUploadFile(path, name, listNamePair);//[api=file/upload, filedata=filedata, context=2] Map<String,String> ResMap=SetParamDao.getJsonMap(ttString); return ResMap; }
// 构造源参数aaa public static String GetJson(List<NameValuePair> myParameter) { // 初始化参数 List<NameValuePair> jsonvalue = initParameter(myParameter); // 获得字符串 String UrlPam = getStrUrlPam(jsonvalue); // 签名字符串 String HamacSha1 = HMACSHA1.hmac_sha1(MySetting.Secret + "&", URLEncoder.encode("&" + UrlPam)).trim(); jsonvalue.add(new BasicNameValuePair(T.OtherConst.S, HamacSha1)); String myjson = newGetWebResult(jsonvalue); System.out.print("返回数据"+myjson.toString()); return myjson.toString(); }