android开发之上传图片和调用相机以及相册
2015-05-19 15:34
676 查看
看图分析:
界面UI布局:
Dialog以及UI布局:
Dialog:
UI布局:
调用相机拍照选取图片:
通过Intent(意图)调用系统相机
调用相册选取图片:
通过Intent(意图)调用系统相册
选取图片后压缩图片:
上传图片:
使用AsyncTask结合Http与服务器进行交互来完成文件上传
AsyncTask
Http与服务器进行交互
自定义上传进度
Notification 状态栏通知
状态栏通知UI布局:
示例代码戳Here
界面UI布局:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" android:background="@color/color_white"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="@dimen/size_50dp" > <TextView android:id="@+id/viewpager_item_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/size_14dp" android:padding="@dimen/size_14dp" android:textColor="@color/color_000" android:textSize="@dimen/size_14dp" /> <RelativeLayout android:id="@+id/viewpager_item_viewed" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/viewpager_item_title" android:layout_marginLeft="@dimen/size_14dp" android:layout_marginRight="@dimen/size_14dp" android:background="@drawable/bg_ed_shape" > <EditText android:id="@+id/viewpager_item_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@null" android:gravity="top" android:hint="@string/viewpager_edittext_hint" android:inputType="textMultiLine" android:maxLines="50" android:minHeight="@dimen/size_150dp" android:padding="@dimen/size_14dp" android:textColor="@color/color_000" android:textColorHint="@color/color_c" android:textSize="@dimen/size_14dp" /> <LinearLayout android:id="@+id/viewpager_item_zp_ll" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/line" android:orientation="horizontal" android:padding="@dimen/size_10dp" android:visibility="gone" > <ImageView android:id="@+id/viewpager_item_zp_1" android:layout_width="@dimen/size_40dp" android:layout_height="@dimen/size_40dp" android:background="@drawable/xk" /> <ImageView android:id="@+id/viewpager_item_zp_2" android:layout_width="@dimen/size_40dp" android:layout_height="@dimen/size_40dp" android:layout_marginLeft="@dimen/size_10dp" android:background="@drawable/xk" android:visibility="gone" /> <ImageView android:id="@+id/viewpager_item_zp_3" android:layout_width="@dimen/size_40dp" android:layout_height="@dimen/size_40dp" android:layout_marginLeft="@dimen/size_10dp" android:background="@drawable/xk" android:visibility="gone" /> <ImageView android:id="@+id/viewpager_item_zp_4" android:layout_width="@dimen/size_40dp" android:layout_height="@dimen/size_40dp" android:layout_marginLeft="@dimen/size_10dp" android:background="@drawable/xk" android:visibility="gone" /> </LinearLayout> <ImageView android:id="@+id/line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_below="@+id/viewpager_item_edittext" android:background="@color/color_c9" /> <RelativeLayout android:id="@+id/viewpager_item_viewxj" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/viewpager_item_edittext" android:layout_margin="1dp" android:background="@color/color_bg_hui" > <ImageView android:id="@+id/viewpager_item_xj" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="@dimen/size_13dp" android:src="@drawable/xj" /> </RelativeLayout> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/viewpager_item_viewxj" /> </RelativeLayout> <TextView android:id="@+id/viewpager_item_next" style="@style/bt_style_bgtowhite" android:layout_below="@+id/viewpager_item_viewed" android:layout_marginTop="@dimen/size_27dp" /> </RelativeLayout> </ScrollView>
Dialog以及UI布局:
Dialog:
public class Pop_Viewpager_Item_Pz { private static final int CAMERA_WITH_DATA = 1001; private static final int PHOTO_PICKED_WITH_DATA = 1002; private Activity activity; private TextView viewpager_pop_pz_pz, viewpager_pop_pz_xc, viewpager_pop_pz_back; public Dialog mDialog; public Dialog getmDialog() { return mDialog; } public void setmDialog(Dialog mDialog) { this.mDialog = mDialog; } public Pop_Viewpager_Item_Pz(Activity context) { activity = context; mDialog = new Dialog(context, R.style.Setting_Question_Submit_Dialog_Style); mDialog.setContentView(R.layout.viewpager_item_pop_pz); Window window = mDialog.getWindow(); WindowManager wm = context.getWindowManager(); Display d = wm.getDefaultDisplay(); // 获取屏幕宽、高用 WindowManager.LayoutParams p = window.getAttributes(); p.width = (int) (d.getWidth() * 0.85); window.setAttributes(p); mDialog.setFeatureDrawableAlpha(Window.FEATURE_OPTIONS_PANEL, 0); window.setWindowAnimations(android.R.anim.fade_in); viewpager_pop_pz_pz = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_pz); viewpager_pop_pz_pz.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { doTakePhoto(); //拍照选取图片 } }); viewpager_pop_pz_xc = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_xc); viewpager_pop_pz_xc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { doSelectImageFromLoacal(); //从相册中选取图片 } }); viewpager_pop_pz_back = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_back); viewpager_pop_pz_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { dismiss(); } }); } public void show() { mDialog.show(); } public void dismiss() { mDialog.dismiss(); } }
UI布局:
<?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/viewpager_pop_pz_iv" android:layout_width="match_parent" android:layout_height="@dimen/size_20dp" android:layout_alignParentBottom="true" /> <TextView android:id="@+id/viewpager_pop_pz_back" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/viewpager_pop_pz_iv" android:layout_marginTop="@dimen/size_12dp" android:background="@drawable/viewpager_pop_pz_shape" android:clickable="true" android:gravity="center" android:padding="@dimen/size_12dp" android:text="取消" android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv" android:textSize="@dimen/size_20dp" /> <RelativeLayout android:id="@+id/viewpager_pop_pz" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/viewpager_pop_pz_back" android:background="@drawable/viewpager_pop_pz_shape" > <TextView android:id="@+id/viewpager_pop_pz_pz" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:gravity="center" android:padding="@dimen/size_12dp" android:text="拍照" android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv" android:textSize="@dimen/size_20dp" /> <ImageView android:id="@+id/viewpager_pop_pz_line" android:layout_width="match_parent" android:layout_height="0.5dp" android:layout_below="@+id/viewpager_pop_pz_pz" android:background="@color/color_c9" /> <TextView android:id="@+id/viewpager_pop_pz_xc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/viewpager_pop_pz_line" android:clickable="true" android:gravity="center" android:padding="@dimen/size_12dp" android:text="从相册选取" android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv" android:textSize="@dimen/size_20dp" /> </RelativeLayout> </RelativeLayout>
调用相机拍照选取图片:
通过Intent(意图)调用系统相机
/** * 拍照获取图片 */ public static void takePhoto(Activity activity) { String SDState = Environment.getExternalStorageState(); if (SDState.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); ContentValues values = new ContentValues(); photoUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri); activity.startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO); } else { Toast.makeText(activity, "内存卡不存在", Toast.LENGTH_LONG).show(); } }
调用相册选取图片:
通过Intent(意图)调用系统相册
/** * 从本地手机中选择图片 */ private void doSelectImageFromLoacal() { Intent localIntent = new Intent(); localIntent.setType("image/*"); localIntent.setAction(Intent.ACTION_GET_CONTENT); localIntent.addCategory(Intent.CATEGORY_OPENABLE); Intent localIntent2 = Intent.createChooser(localIntent, "选择图片"); activity.startActivityForResult(localIntent2, PHOTO_PICKED_WITH_DATA); mDialog.dismiss(); }
选取图片后压缩图片:
/** * 压缩图片. */ private String ys_img(String img_path) { String[] path_arr = img_path.split("/"); String[] name_arr = path_arr[path_arr.length - 1].split("\\."); String path = File_Tool.SDPATH + "image/" + name_arr[0] + ".png"; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 获取这个图片的宽和高 Bitmap bitmap = BitmapFactory.decodeFile(img_path, options); // 此时返回bm为空 options.inJustDecodeBounds = false; // 计算缩放比 int be = (int) (options.outHeight / 60); if (be <= 0) be = 1; options.inSampleSize = be; // 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦 bitmap = BitmapFactory.decodeFile(img_path, options); int w = bitmap.getWidth(); int h = bitmap.getHeight(); ImageView iv = new ImageView(this); iv.setImageBitmap(bitmap); //bitmap = compressImage(Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false)); // 这样我们就可以读取较大的图片而不会内存溢出了。如果你想把压缩后的图片保存在Sdcard上的话就很简单了: File file = new File(path); try { FileOutputStream out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.PNG, 50, out)) { out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return path; }
上传图片:
使用AsyncTask结合Http与服务器进行交互来完成文件上传
AsyncTask
/** * 提交用户文字以及图片答案接口数据. * * @author wanglei */ class Put_UserAnser_Task extends AsyncTask<String, Integer, String> { ArrayList<String> id_list = new ArrayList<String>(); @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... arg0) { MyPhotoApp_Data_Application myphoto = (MyPhotoApp_Data_Application) getApplication(); //TODO String url = myphoto.getUrl_host() + "port&a=userPaperAnswer" + "&sid=" + myphoto.getSessionid(), resurt = ""; ArrayList<NameValuePair> val_list = new ArrayList<NameValuePair>(); try { val_list.add(new BasicNameValuePair("is_img", is_img > 0 ? "1" : "0")); // $is_img=1有照片, resurt = HttpUtil.getData(MainActivity.this, url, val_list, HttpUtil.METHOD_POST); } catch (ConnectException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return resurt; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if ("1".equals(result)) { if (is_img > 0) { int img_sum = 0; Intent intent = new Intent(MainActivity.this, UploadImage_Activity.class); for (int i=0;i<4;i++) { img_sum++; id_list.add(""+(i+1)); } intent.putExtra("img_sum", img_sum); intent.putStringArrayListExtra("id_list", id_list); intent.putStringArrayListExtra("lists", lists); MainActivity.this.startActivityForResult(intent, 101); MainActivity.this.finish(); } else { toast.setText("提交成功"); toast.show(); } } else { toast.setText("提交失败"); toast.show(); } } }
Http与服务器进行交互
public class HttpUtil { public static final int METHOD_GET = 1; public static final int METHOD_POST = 2; public static String getData(Context context, String uri, List<NameValuePair> params, int method) throws ConnectException, IOException { HttpEntity entity = getEntity(uri, params, method); if(entity != null) { return EntityUtils.toString(entity); } else { return "error"; } } public static HttpEntity getEntity(String uri, List<NameValuePair> params, int method) throws ConnectException, IOException { HttpEntity entity = null; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); HttpUriRequest request = null; switch (method) { case METHOD_GET: StringBuilder sb = new StringBuilder(uri); if (params != null && !params.isEmpty()) { sb.append('?'); for (NameValuePair pair : params) { sb.append(pair.getName()).append('=').append(pair.getValue()).append('&'); } sb.deleteCharAt(sb.length() - 1); } request = new HttpGet(sb.toString()); break; case METHOD_POST: request = new HttpPost(uri); if (params != null && !params.isEmpty()) { UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(params, "UTF-8"); ((HttpPost) request).setEntity(reqEntity); } break; } HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { entity = response.getEntity(); } else { } return entity; } }
自定义上传进度
public class CircleProgressBar extends View { private int maxProgress = 100; private int progress = 0; private int progressStrokeWidth = 20; // 画圆所在的距形区域 RectF oval; Paint paint; public CircleProgressBar(Context context, AttributeSet attrs) { super(context, attrs); oval = new RectF(); paint = new Paint(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = this.getWidth(); int height = this.getHeight(); if (width != height) { int min = Math.min(width, height); width = min; height = min; } paint.setAntiAlias(true); // 设置画笔为抗锯齿 paint.setColor(Color.WHITE); // 设置画笔颜色 canvas.drawColor(Color.TRANSPARENT); // 白色背景 paint.setStrokeWidth(progressStrokeWidth); // 线宽 paint.setStyle(Style.STROKE); oval.left = progressStrokeWidth / 2; // 左上角x oval.top = progressStrokeWidth / 2; // 左上角y oval.right = width - progressStrokeWidth / 2; // 左下角x oval.bottom = height - progressStrokeWidth / 2; // 右下角y canvas.drawArc(oval, -90, 360, false, paint); // 绘制白色圆圈,即进度条背景 paint.setColor(Color.RED); canvas.drawArc(oval, -90, ((float) progress / maxProgress) * 360, false, paint); // 绘制进度圆弧,这里是蓝色 paint.setStrokeWidth(1); String text = progress + "%"; int textHeight = height / 4; paint.setTextSize(textHeight); int textWidth = (int) paint.measureText(text, 0, text.length()); paint.setStyle(Style.FILL); canvas.drawText(text, width / 2 - textWidth / 2, height / 2 + textHeight / 2, paint); } public int getMaxProgress() { return maxProgress; } public void setMaxProgress(int maxProgress) { this.maxProgress = maxProgress; } public void setProgress(int progress) { this.progress = progress; this.invalidate(); } /** * 非UI线程调用 */ public void setProgressNotInUiThread(int progress) { this.progress = progress; this.postInvalidate(); } }
Notification 状态栏通知
private NotificationManager manager; private Notification notif; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: notif.contentView.setTextViewText(R.id.content_view_text1, len + " %"); notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false); manager.notify(0, notif); break; case 1: manager.cancel(0); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.upload_image); init_PutImg(); } private void init_PutImg() { PendingIntent pIntent = PendingIntent.getActivity(this, 0, new Intent(), 0); manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notif = new Notification(); notif.icon = R.drawable.ic_launcher; notif.tickerText = "正在上传作答文件"; notif.flags = Notification.FLAG_AUTO_CANCEL; // 通知栏显示所用到的布局文件 notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view); notif.contentIntent = pIntent; manager.notify(0, notif); manager.cancel(0); }
状态栏通知UI布局:
<?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/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="@dimen/size_10dp" android:layout_marginRight="@dimen/size_10dp" android:background="@drawable/ic_launcher" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="@dimen/size_10dp" android:layout_toRightOf="@+id/icon" > <TextView android:id="@+id/content_view_text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="@dimen/size_8dp" android:text="0 %" android:textColor="@color/color_c50619" android:textSize="@dimen/size_14dp" /> <ProgressBar android:id="@+id/content_view_progress" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="fill_parent" android:layout_height="1dp" android:layout_below="@+id/content_view_text1" android:layout_marginTop="14dp" android:max="100" android:progressDrawable="@drawable/barcolor" /> </RelativeLayout> </RelativeLayout>
示例代码戳Here
相关文章推荐
- Android调用手机相机和相册拿到图片保存上传
- Android开发,调用相册图片或者调用相机进行拍照获取图片
- Android开发基础 调用相机 系统相册(并对图片进行压缩处理)
- Android 拍照以及一些常用的处理,例如将图片显示到相册(包含了安卓系统6.0以上调用相机的处理)
- 安卓开发小米4,酷派 手机适配和调用系统相机相册做图片上传的问题
- Android中相机拍摄照片,以及相册选择图片压缩上传(压缩后保存进SD中)(可用于修改头像等)
- Android开发中调用系统相册上传图片到服务器OPPO等部分手机上出现短暂的显示桌面问题的解决方法
- android中调用相机、相册 以及图片压缩,文件压缩
- Android手机调用系统相机拍照、裁剪以及获取Url上传图片
- Android WebView 选择图片并上传(调用相机拍照/相册/选择文件)
- Android开发 调用系统相机相册图片功能,解决小米手机拍照或者图片横竖相反问题,及小米手机相册图片路径问题
- android 开发 web页面调取相册相机 上传图片
- [置顶] 【Android开发技巧】 关于Webview拍照或从相册上传图片处理总结
- Android 调用相机APP获取拍照图片和从相册选择图片
- Android调用系统相机、相册功能,适配6.0权限获取以及7.0以后获取URI(兼容多版本)
- 调用系统相机、相册、剪裁图片并上传(常用于上传头像,兼容Android7.0)
- Android 调用系统相机拍照并且显示在相册中,以及中间可能会遇到的一些问题的解决
- 微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传
- android 调用系统相册选取照片或者打开相机拍照获取图片,返回时回到手机桌面,然后才会跳转到当前activity
- android 调用系统相册选取照片或者打开相机拍照获取图片