0

这是我的源代码,当单击浏览按钮从图库中拍照或使用相机拍摄时提供两个选项我怎么做到的?

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class AddEditCountry extends Activity {
 private long rowID; 
 private EditText nameEt;
 private EditText capEt;
 private EditText codeEt;
 private EditText Donedate;
 private EditText Notes;
 private EditText Person;
 private  ImageView imageView1;
public  static Bitmap yourSelectedImage = null;
public static byte[] blob = null;
private final int CAMERA_PICTURE = 1;
private final int GALLERY_PICTURE = 2;
private Intent pictureActionIntent = null;
//public static        byte[] blob = new byte[2048];

   @Override
   public void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.add_country);

      nameEt = (EditText) findViewById(R.id.Address);
      capEt = (EditText) findViewById(R.id.Stage);
      codeEt = (EditText) findViewById(R.id.Dueby);

      Donedate = (EditText) findViewById(R.id.Donedate);

      Notes = (EditText) findViewById(R.id.Notes);
      Person = (EditText) findViewById(R.id.Person);

      imageView1 = (ImageView) findViewById(R.id.imageView1);
      Button Browse = (Button) findViewById(R.id.Browse);
      Browse.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {               
        //      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //      intent.setType("image/*");
         //     startActivityForResult(intent, 0);

                startDialog();
            }
        });        

      Bundle extras = getIntent().getExtras(); 

      if (extras != null)
      {
         rowID = extras.getLong("row_id");
         nameEt.setText(extras.getString("name"));  
         capEt.setText(extras.getString("cap"));  
         codeEt.setText(extras.getString("code"));  
         Donedate.setText(extras.getString("Location"));  
         Notes.setText(extras.getString("Notes")); 
         Person.setText(extras.getString("Person")); 
         }

      Button saveButton =(Button) findViewById(R.id.saveBtn);
      saveButton.setOnClickListener(new OnClickListener() {

          public void onClick(View v) 
          {
             if (nameEt.getText().length() != 0)
             {
                AsyncTask<Object, Object, Object> saveContactTask = 
                   new AsyncTask<Object, Object, Object>() 
                   {
                      @Override
                      protected Object doInBackground(Object... params) 
                      {
                         saveContact();
                         return null;
                      }

                      @Override
                      protected void onPostExecute(Object result) 
                      {
                         finish();
                      }
                   }; 

                saveContactTask.execute((Object[]) null); 
             }

             else
             {
                AlertDialog.Builder alert = new  
 AlertDialog.Builder(AddEditCountry.this);
                alert.setTitle(R.string.errorTitle); 
                alert.setMessage(R.string.errorMessage);
                alert.setPositiveButton(R.string.errorButton, null); 
                alert.show();
             }
          } 
     });
   }

   private void saveContact() 
   {

//     byte[] blob = new byte[2048];

       ByteArrayOutputStream outStr = new ByteArrayOutputStream();
       yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
        blob = outStr.toByteArray();

      DatabaseConnector dbConnector = new DatabaseConnector(this);

      if (getIntent().getExtras() == null)
      {
          dbConnector.insertContact(nameEt.getText().toString(),
                  capEt.getText().toString(),
                  codeEt.getText().toString(),
                  Donedate.getText().toString(),
                  Notes.getText().toString(),
                  Person.getText().toString()
                  ,blob
                  );
      }
      else
      {
         dbConnector.updateContact(rowID,
            nameEt.getText().toString(),
            capEt.getText().toString(), 
            codeEt.getText().toString(), 
            Donedate.getText().toString(),
         Notes.getText().toString(),
          Person.getText().toString()
          , blob
         );
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent  
    imageReturnedIntent) {
       super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

       if (requestCode == GALLERY_PICTURE) {
            Uri uri = imageReturnedIntent.getData();
            if (uri != null) {
                // User had pick an image.
                Cursor cursor = getContentResolver().query(uri, new String[]  
     {  android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                cursor.moveToFirst();
                final String imageFilePath = cursor.getString(0);
                File photos = new File(imageFilePath);
                yourSelectedImage = decodeFile(photos);
                yourSelectedImage =  
    Bitmap.createScaledBitmap(yourSelectedImage, 150, 150, true);
                imageView1.setImageBitmap(yourSelectedImage);
                cursor.close();
            }
            else {
                Toast toast = Toast.makeText(this, "No Image is selected.",  
   Toast.LENGTH_LONG);
                toast.show();
            }
        }
        else if (requestCode == CAMERA_PICTURE) {
            if (imageReturnedIntent.getExtras() != null) {
                // here is the image from camera
                yourSelectedImage = (Bitmap)  
  imageReturnedIntent.getExtras().get("data");
                imageView1.setImageBitmap(yourSelectedImage);
            }
        }
    }
   private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < 
 REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale++;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null,  
   o2);
        }
        catch (FileNotFoundException e) {
        }
        return null;
    }

    private void startDialog() {
        AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
        myAlertDialog.setTitle("Upload Pictures Option");
        myAlertDialog.setMessage("How do you want to set your picture?");

        myAlertDialog.setPositiveButton("Gallery", new 
  DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT,  
  null);
                pictureActionIntent.setType("image/*");
                pictureActionIntent.putExtra("return-data", true);
                startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
            }
        });

        myAlertDialog.setNegativeButton("Camera", new  
  DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                pictureActionIntent = new  
  Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(pictureActionIntent, CAMERA_PICTURE);
            }
        });
        myAlertDialog.show();
    }
}
4

2 回答 2

1

试试这个 ::

 private void SelectPhotoFromCamera() 
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory(),
                "/DCIM" + ".jpg");

           if(file.isDirectory()) 
           {
                 //DO SOMETHING
           }                   
           else
           {
                  //DO SOMETHING
           }   
        outputFileUri = Uri.fromFile(file);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(intent, SELECT_PICTURE_CAMERA);
    }
于 2012-12-18T06:01:56.233 回答
0

看看这个帖子,也有类似的问题。您需要使用媒体扫描仪。 Android - 为什么我保存的图像没有出现在手机的默认图库中?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;


public class ImageSaver {
    private String TAG = "ImageSaver";
    private Context context;
    private String FILENAME_LEADER = "bijintokei";
    private String DOWNLOAD_FOLDER = "download";
    private String STORAGE_DESTINATION = "/sdcard";
    private CompressFormat COMPRESS_FORMAT = CompressFormat.JPEG;

    /**
     * Return file extension
     * 
     * @return
     */
    private String getFileExtention() {
        String result = "bmp";
        if (COMPRESS_FORMAT.equals(CompressFormat.JPEG)) {
            result = "jpg";
        }
        if (COMPRESS_FORMAT.equals(CompressFormat.PNG)) {
            result = "png";
        }
        return result;
    }

    /**
     * Constructor
     * 
     * @param context
     */
    public ImageSaver(Context context) {
        this.context = context;
    }

    /**
     * Return appropriate file path for saving
     * 
     * @param hhmm
     * @return File path
     */
    public String getFilePath4Saving(String hhmm) {
        String fileName = "", destination = this.getDefaultLocation(), filePath = "";
        int i = 0;
        File file;
        do {
            fileName = getMixedFileName(hhmm, i++);
            filePath = String.format("%s/%s", destination, fileName);
            file = new File(filePath);
        } while (file.exists());
        Log.d(TAG, "File path for saving: " + filePath);
        return filePath;

    }

    /**
     * Return a mixed file name from: - FILENAME_LEADER - Specified time - Order
     * number
     * 
     * @param hhmm
     * @param i
     * @return
     */
    private String getMixedFileName(String hhmm, int i) {
        String fileName = String.format("%s%s", FILENAME_LEADER, hhmm);
        String extension = getFileExtention();
        String result = String.format("%s.%s", fileName, extension);
        if (i > 0) {
            result = String.format("%s-%d.%s", fileName, i, extension);
        }
        return result;
    }

    /**
     * Make sure Download folder is exists in the specified path
     */
    private boolean MakeSureFolderIsExists(String path, String folder) {
        File file = new File(path + "/" + folder);
        boolean result = true;
        if (!file.exists()) {
            result = file.mkdir();
            Log.d(TAG,
                    "Create folder " + path + "/" + folder + ": "
                            + Boolean.toString(result));
        }
        return result;
    }

    /**
     * Return default location for saving image
     * 
     * @return By default return external storage
     */
    private String getDefaultLocation() {
        String result = this.STORAGE_DESTINATION;
        if (MakeSureFolderIsExists(result, DOWNLOAD_FOLDER)) {
            result = result + "/" + DOWNLOAD_FOLDER;
        }
        return result;
    }

    /**
     * Save bitmap for hhmm minute to default destination
     * 
     * @param bitmap
     * @param hhmm
     * @throws IOException
     */
    public void saveImage(Bitmap bitmap, String hhmm) throws IOException {
        Log.d(TAG, "Saving image: " + hhmm);
        String filePath = getFilePath4Saving(hhmm);
        File fo = new File(filePath);
        FileOutputStream out = new FileOutputStream(fo);
        bitmap.compress(CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        requestMediaScannerRefesh();
    }

    /**
     * Require Media Scanner refresh
     */
    private void requestMediaScannerRefesh() {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
                .parse("file://" + Environment.getExternalStorageDirectory())));
    }
    public static Bitmap decodeFile(File f,int screenHeight,
            int screenWidth){
        Bitmap b = null;
        try {

            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            FileInputStream fis = new FileInputStream(f);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();

            int scale = 1;
            if (o.outHeight > screenHeight || o.outWidth > screenWidth) {
                scale = (int)Math.pow(2, (int) Math.round(Math.log(screenHeight / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            fis = new FileInputStream(f);
            b = BitmapFactory.decodeStream(fis, null, o2);
            fis.close();
        } catch (IOException e) {
        }
        return b;
    }
}
于 2012-12-18T06:09:18.643 回答