Android設(shè)置拍照或者上傳本地圖片的示例
前幾天,我們客戶端這邊收到了市場部的一個(gè)需求,需要在我們訂單成交后,我們的客戶端有一個(gè)上傳交易憑證的功能,那么如何在Android實(shí)現(xiàn)上傳圖片的這個(gè)功能呢?在我進(jìn)行編碼之前,我先問自己幾個(gè)問題。
第一, 圖片是直接選擇圖庫里的,還是需要拍照和選擇圖片兩個(gè)選項(xiàng)?
因?yàn)樵谶x擇圖片的時(shí)候,會(huì)有一個(gè)拍照的按鈕,也可以實(shí)現(xiàn)拍照的功能。
第二, 需不需要本地緩存?
本地緩存值得是,在我們的圖片上傳后,是否在下次直接顯示,而不是從服務(wù)器讀取。
第三,圖片是否需要壓縮?
眾所周知,圖片這種資源,因?yàn)轶w積較大,在網(wǎng)絡(luò)上傳輸還是很慢的,所以,我們需要在我們的傳輸時(shí),適當(dāng)?shù)膶ξ募拇笮∵M(jìn)行壓縮,那么就要根據(jù)我們自身的需求,按照一定的比例來進(jìn)行壓縮。
在思考完這幾個(gè)問題后,根據(jù)我們自己的需求,我們在上傳時(shí)有兩個(gè)選項(xiàng)的,一個(gè)是拍照,一個(gè)是選擇圖片,另外我們需要做本地緩存,還有,圖片上傳不需要壓縮。
那么我們就可以開始實(shí)現(xiàn)了,首先在我們的主fragment里,添加如下代碼,如果你是activity,當(dāng)然也可以。
做一個(gè)ImageView,作為我們上傳的圖像。
mPic1 = (ImageView) view.findViewById(R.id.ImageView01);
nbsp; mPic1.setOnClickListener(mPhotoListener);
private View.OnClickListener mPhotoListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.ImageView01) {
Intent popupIntent = new Intent(getActivity(), PopupActivity.class);
mPhotoId = id;
startActivityForResult(popupIntent, 1);
}
}
};
然后,我們跳轉(zhuǎn)到另外一個(gè)PopupActivity,讓我們選擇,
PopupActivity.Java
package com.chuanlaoda.android.activity;
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.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.chuanloada.android.R;
public class PopupActivity extends Activity implements OnClickListener {
private Button btn_take_photo, btn_pick_photo, btn_cancel;
private LinearLayout layout;
private Intent intent;
private Button showList;
private Button uploadNow;
private String mCurrentPhotoPath;
private Bitmap sourcePic;
private File dir = null;
private String picName = null;
private String uploadFile = null;
static Uri capturedImageUri=null;
private Bitmap bitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
intent = getIntent();
btn_take_photo = (Button) this.findViewById(R.id.btn_take_photo);
btn_pick_photo = (Button) this.findViewById(R.id.btn_pick_photo);
btn_cancel = (Button) this.findViewById(R.id.btn_cancel);
layout = (LinearLayout) findViewById(R.id.pop_layout);
layout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "提示:點(diǎn)擊空白地方可以關(guān)閉",
Toast.LENGTH_SHORT).show();
}
});
btn_cancel.setOnClickListener(this);
btn_pick_photo.setOnClickListener(this);
btn_take_photo.setOnClickListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
finish();
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (data != null) {
if (data.getExtras() != null)
{
bitmap = (Bitmap) data.getExtras().get("data");
intent.putExtras(data.getExtras());
intent.putExtra("uri", capturedImageUri);
intent.putExtra("requestCode", requestCode);
intent.putExtra("image", bitmap);
}
if (data.getData() != null)
intent.setData(data.getData());
}
setResult(requestCode, intent);
finish();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_take_photo:
dispatchTakePictureIntent();
break;
case R.id.btn_pick_photo:
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 2);
} catch (ActivityNotFoundException e) {
}
break;
case R.id.btn_cancel:
finish();
break;
default:
break;
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
capturedImageUri = Uri.fromFile(photoFile);
if (photoFile != null) {
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(takePictureIntent, 1);
}
}
}
}
Popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/pop_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:background="@drawable/btn_style_alert_dialog_background"
>
<Button
android:id="@+id/btn_take_photo"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="拍照"
android:background="@drawable/btn_style_alert_dialog_button"
android:textStyle="bold"
/>
<Button
android:id="@+id/btn_pick_photo"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="5dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="從相冊選擇"
android:background="@drawable/btn_style_alert_dialog_button"
android:textStyle="bold"
/>
<Button
android:id="@+id/btn_cancel"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="15dip"
android:layout_marginBottom="15dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="取消"
android:background="@drawable/btn_style_alert_dialog_cancel"
android:textColor="#ffffff"
android:textStyle="bold"
/>
</LinearLayout>
</RelativeLayout>
接下來就是我們需要在我們的主fragment (或者activity)中添加onActivityResult.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
photo = (ImageView) mView.findViewById(mPhotoId);
String pfid=String.valueOf(BusinessDetailsFragment.getPosition(mPhotoId) + 1);
String gsid=String.valueOf(mBusinessId);
String cur_date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
switch (resultCode) {
case 1:
if (data != null) {
Uri mImageCaptureUri = (Uri) data.getExtras().get("uri");
if (mImageCaptureUri != null) {
Bitmap image;
try {
//image = MediaStore.Images.Media.getBitmap(this.getActivity().getContentResolver(), mImageCaptureUri);
image = (Bitmap) data.getExtras().get("image");
String fileFullPath = PhotoAPI.savePicsToSdcard(image, mFileLoc);
PromptUtils.showProgressDialog(getActivity(), "正在上傳照片");
mResult = PhotoAPI.uploadFile(gsid, pfid, fileFullPath);
Cache.addLastPhotoPath(pfid, fileFullPath);
Cache.addLastPhotoDate(gsid, cur_date);
PromptUtils.dismissProgressDialog();
showDialog(mResult);
if (image != null) {
photo.setImageBitmap(image);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap image = extras.getParcelable("data");
String fileFullPath = PhotoAPI.savePicsToSdcard(image, mFileLoc);
PromptUtils.showProgressDialog(getActivity(), "正在上傳照片");
mResult = PhotoAPI.uploadFile(gsid, pfid, fileFullPath);
PromptUtils.dismissProgressDialog();
Cache.addLastPhotoPath(pfid, fileFullPath);
Cache.addLastPhotoDate(gsid, cur_date);
showDialog(mResult);
if (image != null) {
photo.setImageBitmap(image);
}
}
}
}
break;
case 2:
if (data != null) {
Uri mImageCaptureUri = data.getData();
if (mImageCaptureUri != null) {
Bitmap image;
try {
image = MediaStore.Images.Media.getBitmap(this.getActivity().getContentResolver(), mImageCaptureUri);
String fileFullPath = getRealPathFromURI(this.getActivity(),mImageCaptureUri);
PromptUtils.showProgressDialog(getActivity(), "正在上傳照片");
mResult = PhotoAPI.uploadFile(gsid, pfid, fileFullPath);
PromptUtils.dismissProgressDialog();
Cache.addLastPhotoPath(pfid, fileFullPath);
Cache.addLastPhotoDate(gsid, cur_date);
showDialog(mResult);
if (image != null) {
photo.setImageBitmap(image);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Bundle extras = data.getExtras();
if (extras != null) {
String fileFullPath = getRealPathFromURI(this.getActivity(),mImageCaptureUri);
PromptUtils.showProgressDialog(getActivity(), "正在上傳照片");
mResult = PhotoAPI.uploadFile(gsid, pfid, fileFullPath);
PromptUtils.dismissProgressDialog();
Cache.addLastPhotoPath(pfid, fileFullPath);
Cache.addLastPhotoDate(gsid, cur_date);
Bitmap image = extras.getParcelable("data");
if (image != null) {
photo.setImageBitmap(image);
}
}
}
}
break;
default:
break;
}
}
另外,我們處理圖片上傳的代碼在這里。
class UploadThread extends Thread {
private String result = "";
private String actionUrl;
private String uploadFile;
public UploadThread(String gsid, String pfid, String uploadFile) {
String baseUrl = APIConfig.getAPIHost() + "uploadProof";
this.actionUrl=baseUrl+"&gsid=" + gsid + "&pfid="+pfid;
this.uploadFile = uploadFile;
}
@Override
public void run() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允許Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 設(shè)置傳送的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);
/* 設(shè)置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"GooddShip\";filename=\"" + uploadFile + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadFile);
/* 設(shè)置每次寫入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 從文件讀取數(shù)據(jù)至緩沖區(qū) */
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內(nèi)容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
/* Parse JSON */
JSONObject jObject = new JSONObject(b.toString());
int code = jObject.getInt("Code");
String error = jObject.getString("Error");
String msg = jObject.getString("msg");
if (code == 1) {
/* 將Response顯示于Dialog */
result = "上傳成功";
} else result = "上傳失敗" + error;
/* 關(guān)閉DataOutputStream */
ds.close();
} catch (Exception e) {
result = "上傳失敗" + e;
}
}
然后就可以了,我們最終的效果如下。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android啟動(dòng)相機(jī)拍照并返回圖片
- Android實(shí)現(xiàn)拍照、選擇圖片并裁剪圖片功能
- android 拍照和上傳的實(shí)現(xiàn)代碼
- Android拍照得到全尺寸圖片并進(jìn)行壓縮
- android系統(tǒng)在靜音模式下關(guān)閉camera拍照聲音的方法
- Android實(shí)現(xiàn)調(diào)用系統(tǒng)相冊和拍照的Demo示例
- Android手機(jī)拍照或選取圖庫圖片作為頭像
- Android 7.0中拍照和圖片裁剪適配的問題詳解
- Android中使用Camera類編寫手機(jī)拍照App的實(shí)例教程
- Android調(diào)用手機(jī)拍照功能的方法
- Android開發(fā)實(shí)現(xiàn)拍照功能的方法實(shí)例解析
相關(guān)文章
Android使用GridView實(shí)現(xiàn)日歷的方法
本篇文章主要介紹了Android使用GridView實(shí)現(xiàn)日歷的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
Android中的android:layout_weight使用詳解
layout_weight的作用是設(shè)置子空間在LinearLayout的重要度(控件的大小比重)。layout_weight的值越低,則控件越重要,下面為大家介紹下具體的使用方法2013-06-06
Android訪問php取回json數(shù)據(jù)實(shí)例
Android訪問php取回json數(shù)據(jù),實(shí)現(xiàn)代碼如下,遇到訪問網(wǎng)絡(luò)的權(quán)限不足在AndroidManifest.xml中,需要進(jìn)行如下配置2013-06-06
Android仿新浪微博oauth2.0授權(quán)界面實(shí)現(xiàn)代碼(2)
這篇文章主要為大家詳細(xì)介紹了Android仿新浪微博oauth2.0授權(quán)界面實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
很贊的引導(dǎo)界面效果Android控件ImageSwitcher實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了Android控件ImageSwitcher如何實(shí)現(xiàn)很贊的引導(dǎo)界面的具體代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
Android實(shí)現(xiàn)授權(quán)訪問網(wǎng)頁的方法
這篇文章主要介紹了Android實(shí)現(xiàn)授權(quán)訪問網(wǎng)頁的方法,需要的朋友可以參考下2014-07-07

