轉(zhuǎn)載自 http://aokunsang./blog/1295813
最近需要做手機(jī)拍照【兩種方式:調(diào)用系統(tǒng)相機(jī)(博客最后);自己寫照相機(jī)布局】,,預(yù)覽,,上傳功能。特地研究了下android的手機(jī)拍照,。
參考地址:
http://blog.csdn.net/cfwdl/article/details/5746708
http://mjbb./blog/1018006
http://blog.csdn.net/hellogv/article/details/5962494
1,、上傳文件功能網(wǎng)上很多講的,只要細(xì)心點(diǎn),,按照格式來寫發(fā)送的數(shù)據(jù),,都是沒有問題的。如果遇到問題,,歡迎留言討論,、
2、預(yù)覽使用Gallery和ImageSwitcher就行,,我做的很簡(jiǎn)單(參考代碼),。
----------------------------------------------------------------------------------------------------------------------
修改內(nèi)容:
1、照相功能使用系統(tǒng)自帶照相機(jī)(自己寫的照相機(jī)屬性設(shè)置根據(jù)不同照相機(jī)會(huì)有問題,,所以舍棄)
2、預(yù)覽功能不再使用Gallery+ImageSwitcher;實(shí)用性不強(qiáng),,并且顯示慢且卡。改用異步加載
3、上傳圖片時(shí),,對(duì)圖片進(jìn)行壓縮,,增加上傳速度。
4,、長(zhǎng)按gridView進(jìn)入編輯模式,批量刪除圖片,。參考http://aokunsang./blog/1668902
以此,,希望能做到最好的用戶體驗(yàn)。
附上流程圖:
拍照功能:【預(yù)覽尺寸有知道的朋友留言告知,?!?/span>
- * 拍照
- * @author Administrator
- */
- ublic class TakePhotoAct extends Activity implements SurfaceHolder.Callback{
-
- private static String imgPath = Environment.getExternalStorageDirectory().getPath() + "/"+Const.imageDir;
-
- private SurfaceView surfaceView;
- private SurfaceHolder surfaceHolder;
- private Button takePicView,exitView;
-
- private Camera mCamera;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- /這里我在AndroidManifest.xml的activity中添加了android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
-
-
-
-
-
-
-
-
-
-
-
- takePicView = (Button)this.findViewById(R.id.takepic);
- takePicView.setOnClickListener(TakePicListener);
- exitView = (Button)this.findViewById(R.id.exit);
- exitView.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- finish();
- }
- });
- surfaceView = (SurfaceView)this.findViewById(R.id.surface_camera);
- surfaceHolder = surfaceView.getHolder();
- surfaceHolder.addCallback(this);
- surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
-
- checkSoftStage();
- }
-
-
-
-
- private void checkSoftStage(){
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- / String rootPath = Environment.getExternalStorageDirectory().getPath();
- File file = new File(imgPath);
- if(!file.exists()){
- file.mkdir();
- }
- }else{
- new AlertDialog.Builder(this).setMessage("檢測(cè)到手機(jī)沒有存儲(chǔ)卡,!請(qǐng)插入手機(jī)存儲(chǔ)卡再開啟本應(yīng)用。")
- .setPositiveButton("確定", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).show();
- }
- }
-
-
-
-
- private final OnClickListener TakePicListener = new OnClickListener(){
- @Override
- public void onClick(View v) {
- mCamera.autoFocus(new AutoFoucus());
- }
- };
-
-
-
-
-
-
- private final class AutoFoucus implements AutoFocusCallback{
- @Override
- public void onAutoFocus(boolean success, Camera camera) {
- if(success && mCamera!=null){
- mCamera.takePicture(mShutterCallback, null, mPictureCallback);
- }
- }
- }
-
-
-
-
-
- private final PictureCallback mPictureCallback = new PictureCallback() {
- @Override
- public void onPictureTaken(byte[] data, Camera camera) {
- try {
- String fileName = System.currentTimeMillis()+".jpg";
- File file = new File(imgPath,fileName);
- Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
- bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
- bos.flush();
- bos.close();
-
- Intent intent = new Intent(TakePhotoAct.this,PictureViewAct.class);
- intent.putExtra("imagePath", file.getPath());
- startActivity(intent);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- };
-
-
-
-
- private final ShutterCallback mShutterCallback = new ShutterCallback() {
- public void onShutter() {
- Log.d("ShutterCallback", "...onShutter...");
- }
- };
-
- @Override
-
-
-
- public void surfaceChanged(SurfaceHolder holder, int format, int width,
- int height) {
- Camera.Parameters param = mCamera.getParameters();
-
-
-
- param.setPictureFormat(PixelFormat.JPEG);
-
-
-
-
-
-
-
- param.setPictureSize(Const.width, Const.height);
- mCamera.setParameters(param);
-
-
-
- mCamera.startPreview();
- }
- @Override
-
-
-
- public void surfaceCreated(SurfaceHolder holder) {
- try {
- mCamera = Camera.open();
- mCamera.setPreviewDisplay(holder);
- } catch (IOException e) {
- mCamera.release();
- mCamera = null;
- }
- }
-
- @Override
-
-
-
- public void surfaceDestroyed(SurfaceHolder holder) {
- mCamera.stopPreview();
- if(mCamera!=null) mCamera.release();
- mCamera = null;
- }
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if(keyCode == KeyEvent.KEYCODE_CAMERA){
- mCamera.autoFocus(new AutoFoucus());
- return true;
- }else{
- return false;
- }
- }
xml:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas./apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <SurfaceView
- android:id="@+id/surface_camera"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1"
- />
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
-
- <Button
- android:text="拍照"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/takepic"
- />
- <Button
- android:text="退出"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/exit"
- />
- </LinearLayout>
- </LinearLayout>
預(yù)覽功能:
/**
- * 圖片預(yù)覽
- * @author: aokunsang
- * @date: 2012-8-1
- */
- public class PictureScanAct extends Activity {
-
- private GridView gridView;
- private ImageAdapter imgAdapter;
- private List<String> fileNameList = new ArrayList<String>();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.picturescan);
-
- gridView = (GridView)findViewById(R.id.picture_grid);
- imgAdapter = new ImageAdapter(this);
- gridView.setAdapter(imgAdapter);
- gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- String fileName = fileNameList.get(position);
- startActivity(new Intent(PictureScanAct.this, PictureViewAct.class).putExtra("flag","upload").putExtra("imagePath",fileName));
- }
- });
-
- Toast.makeText(this, "加載圖片中....", Toast.LENGTH_LONG).show();
- new AsyncLoadedImage().execute();
- }
-
-
-
-
- private void addImage(Bitmap... loadImages){
- for(Bitmap loadImage:loadImages){
- imgAdapter.addPhoto(loadImage);
- }
- }
-
-
-
- protected void onDestroy() {
- super.onDestroy();
- final GridView grid = gridView;
- final int count = grid.getChildCount();
- ImageView v = null;
- for (int i = 0; i < count; i++) {
- v = (ImageView) grid.getChildAt(i);
- ((BitmapDrawable) v.getDrawable()).setCallback(null);
- }
- }
-
-
-
-
-
- class AsyncLoadedImage extends AsyncTask<Object, Bitmap, Boolean> {
-
- @Override
- protected Boolean doInBackground(Object... params) {
- File fileDir = new File(Const.imgPath);
- File[] files = fileDir.listFiles();
- boolean result = false;
- if(files!=null){
- for(File file:files){
- String fileName = file.getName();
- if (fileName.lastIndexOf(".") > 0
- && fileName.substring(fileName.lastIndexOf(".") + 1,
- fileName.length()).equals("jpg")){
- Bitmap bitmap;
- Bitmap newBitmap;
- try {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = 10;
- bitmap = BitmapFactory.decodeFile(file.getPath(), options);
- newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 100);
- bitmap.recycle();
- if (newBitmap != null) {
- fileNameList.add(file.getPath());
- publishProgress(newBitmap);
- result = true;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- return result;
- }
- @Override
- public void onProgressUpdate(Bitmap... value) {
- addImage(value);
- }
- @Override
- protected void onPostExecute(Boolean result) {
- if(!result){
- showDialog(1);
- }
- }
- }
- @Override
- protected Dialog onCreateDialog(int id) {
- AlertDialog dialog = new AlertDialog.Builder(PictureScanAct.this).setTitle("溫馨提示").setMessage("暫時(shí)還沒有照片,請(qǐng)先采集照片,!")
- .setPositiveButton("確定", new DialogInterface.OnClickListener(){
- @Override
- public void onClick(DialogInterface dialog, int which) {
- startActivity(new Intent(PictureScanAct.this,TakePhotoAct.class));
- }
- }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).show();
- return dialog;
- }
- }
GridView適配器:
public class ImageAdapter extends BaseAdapter {
- private List<Bitmap> picList = new ArrayList<Bitmap>();
- private Context mContext;
- public ImageAdapter(Context mContext){
- this.mContext = mContext;
- }
-
- @Override
- public int getCount() {
- return picList.size();
- }
-
-
-
-
- @Override
- public Object getItem(int position) {
-
- return picList.get(position);
- }
-
-
-
-
- public void addPhoto(Bitmap loadImage){
- picList.add(loadImage);
- notifyDataSetChanged();
- }
-
-
-
-
- @Override
- public long getItemId(int position) {
-
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView = null;
- if(convertView == null){
- imageView = new ImageView(mContext);
- imageView.setLayoutParams(new GridView.LayoutParams(110, 110));
- imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
- imageView.setPadding(5,5,5,5);
- }else{
- imageView = (ImageView)convertView;
- }
- imageView.setImageBitmap(picList.get(position));
- return imageView;
- }
圖片預(yù)覽界面:
<?xml version="1.0" encoding="utf-8"?>
- <GridView xmlns:android="http://schemas./apk/res/android"
- android:id="@+id/picture_grid"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:numColumns="4"
- android:verticalSpacing="5dip"
- android:horizontalSpacing="5dip"
- android:stretchMode="columnWidth"
- android:columnWidth="120dip"
- android:gravity="center"
- >
- </GridView>
預(yù)覽圖片:
上傳工具類:
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Map;
- import java.util.Map.Entry;
-
- import android.util.Log;
-
- import com.peacemap.photo.po.FileInfo;
-
-
-
-
-
-
- public class PostFile {
-
- private static PostFile postFile = new PostFile();
-
- private final static String LINEND = "\r\n";
- private final static String BOUNDARY = "---------------------------7da2137580612";
- private final static String PREFIX = "--";
- private final static String MUTIPART_FORMDATA = "multipart/form-data";
- private final static String CHARSET = "utf-8";
- private final static String CONTENTTYPE = "application/octet-stream";
-
- private PostFile(){}
- public static PostFile getInstance(){
- return postFile;
- }
-
-
-
-
-
-
-
-
- public String post(String actionUrl,Map<String,String> params,FileInfo[] files){
- try {
- URL url = new URL(actionUrl);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- urlConn.setDoOutput(true);
- urlConn.setDoInput(true);
- urlConn.setUseCaches(false);
- urlConn.setRequestMethod("POST");
- urlConn.setRequestProperty("connection", "Keep-Alive");
- urlConn.setRequestProperty("Charset", CHARSET);
- urlConn.setRequestProperty("Content-Type", MUTIPART_FORMDATA+";boundary="+BOUNDARY);
-
- DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
-
- String entryText = bulidFormText(params);
- Log.i("-------描述信息---------------", entryText);
- dos.write(entryText.getBytes());
-
- StringBuffer sb = new StringBuffer("");
-
- for(FileInfo file : files){
- sb.append(PREFIX).append(BOUNDARY).append(LINEND);
- sb.append("Content-Disposition: form-data; name=\""+file.getFileTextName()+"\"; filename=\""+file.getFile().getAbsolutePath()+"\""+LINEND);
- sb.append("Content-Type:"+CONTENTTYPE+";charset="+CHARSET+LINEND);
- sb.append(LINEND);
- dos.write(sb.toString().getBytes());
-
- InputStream is = new FileInputStream(file.getFile());
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- dos.write(buffer, 0, len);
- }
- is.close();
- dos.write(LINEND.getBytes());
- }
-
- byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
- dos.write(end_data);
- dos.flush();
-
-
-
-
- int code = urlConn.getResponseCode();
- if(code!=200){
- urlConn.disconnect();
- return "";
- }else{
- BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
- String result = "";
- String line = null;
- while((line = br.readLine())!=null){
- result += line;
- }
- br.close();
- urlConn.disconnect();
- return result;
- }
- } catch (Exception e) {
- Log.e("--------上傳圖片錯(cuò)誤--------", e.getMessage());
- return null;
- }
- }
-
-
-
-
-
-
-
-
- public String post(String actionUrl,Map<String,String> params,FileInfo fileInfo){
- return post(actionUrl, params, new FileInfo[]{fileInfo});
- }
-
-
-
-
-
-
- private String bulidFormText(Map<String,String> paramText){
- if(paramText==null || paramText.isEmpty()) return "";
- StringBuffer sb = new StringBuffer("");
- for(Entry<String,String> entry : paramText.entrySet()){
- sb.append(PREFIX).append(BOUNDARY).append(LINEND);
- sb.append("Content-Disposition:form-data;name=\""
- + entry.getKey() + "\"" + LINEND);
-
- sb.append(LINEND);
- sb.append(entry.getValue());
- sb.append(LINEND);
- }
- return sb.toString();
- }
-
-
-
-
-
- private String buildFromFile(FileInfo[] files){
- StringBuffer sb = new StringBuffer();
- for(FileInfo file : files){
- sb.append(PREFIX).append(BOUNDARY).append(LINEND);
- sb.append("Content-Disposition: form-data; name=\""+file.getFileTextName()+"\"; filename=\""+file.getFile().getAbsolutePath()+"\""+LINEND);
- sb.append("Content-Type:"+CONTENTTYPE+";charset="+CHARSET+LINEND);
- sb.append(LINEND);
- }
- return sb.toString();
- }
- }
上傳圖片時(shí)對(duì)圖片進(jìn)行壓縮處理(壓縮處理程序):
/**
- * 壓縮圖片上傳
- * @param picPath
- * @return
- */
- private synchronized File compressPicture(String picPath){
-
- String fileName = picPath.substring(picPath.lastIndexOf("/"));
-
- Bitmap bitmap = BitmapFactory.decodeFile(picPath);
-
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
-
-
- int newWidth = 640;
- int newHeight = 480;
-
-
- float scaleWidth = ((float) newWidth) / width;
- float scaleHeight = ((float) newHeight) / height;
-
-
- Matrix matrix = new Matrix();
-
- matrix.postScale(scaleWidth, scaleHeight);
-
-
-
-
- Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
- width, height, matrix, true);
-
-
- File file = new File(Const.thumbnailPath+fileName);
- try {
- FileOutputStream out = new FileOutputStream(file);
- if(resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){
- out.flush();
- out.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- return new File(picPath);
- }finally{
- if(bitmap!=null && !bitmap.isRecycled()){
- bitmap.recycle();
- }
- if(resizedBitmap!=null && !resizedBitmap.isRecycled()){
- resizedBitmap.recycle();
- }
- }
- return file;
- }
- }
-------------------------------------我是個(gè)華麗的分割線,,哇哈哈-----------------------------------------------
做完這個(gè)拍照后,,感覺功能太簡(jiǎn)單,比如:設(shè)置圖片大小,,白天夜晚照相等等一些系統(tǒng)照相機(jī)帶的功能都沒有,,因此用在項(xiàng)目中感覺不炫。 然后就用了簡(jiǎn)單點(diǎn)的,,直接調(diào)用系統(tǒng)照相機(jī)了,。本來想著簡(jiǎn)單呢,后來也遇到點(diǎn)問題。
(1)根據(jù)Camera Activity返回的時(shí)候,,會(huì)帶一個(gè)名為data的Bitmap對(duì)象,,照片的縮略圖(這個(gè)地方可以做各種修改,我沒用到不說了),,上代碼:
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- checkSoftStage();
-
- try {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- startActivityForResult(intent, TAKE_PICTURE);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
- private void checkSoftStage(){
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- File file = new File(imgPath);
- if(!file.exists()){
- file.mkdir();
- }
- }else{
- new AlertDialog.Builder(this).setMessage("檢測(cè)到手機(jī)沒有存儲(chǔ)卡,!請(qǐng)插入手機(jī)存儲(chǔ)卡再開啟本應(yīng)用。")
- .setPositiveButton("確定", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).show();
- }
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (resultCode == TAKE_PICTURE) {
-
- Bitmap cameraBitmap = (Bitmap) data.getExtras().get("/sdcard/rtest.jpg");
-
- image.setImageBitmap(cameraBitmap);
-
-
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
(2)以上代碼在我的小米手機(jī)上測(cè)試時(shí),出現(xiàn)問題了,。 返回的name為data的Bitmap對(duì)象是個(gè)Null,我發(fā)現(xiàn)小米照完相片之后,他會(huì)先跳到一個(gè)預(yù)覽的界面(系統(tǒng)自帶的頁面),,所以得不到Bitmap對(duì)象了,。
因此我就先保存照片以及其路徑,然后在onActivityResult中獲取圖片,,做業(yè)務(wù)操作,,代碼如下:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- checkSoftStage();
-
- try {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- startActivityForResult(intent, TAKE_PICTURE);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- try {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- String fileName = System.currentTimeMillis()+".jpg";
- newImgPath = imgPath + "/" + fileName;
- Uri uri = Uri.fromFile(new File(imgPath,fileName));
- intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
- startActivityForResult(intent, TAKE_PICTURE);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- protected void onActivityResult(int requestCode,
- int resultCode, Intent data) {
- Log.i("--------圖片路徑---------", "------"+newImgPath+"---------");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
|