2014-11-01 3 views
1

В моей деятельности я хочу поставить в ImageView фотографию с камеры или галереи! Из камеры этот код работает хорошо, а когда я беру изображение из галереи, он работает до тех пор, пока я не выбираю свою фотографию! После этого он не дает мне это в образе просмотра! Кто может мне помочь?Установите ImageView с выбранным изображением из камеры или галереи

Вот это MainActivity код:

public class MainActivity extends Activity { 
    private Button mTakePhoto; 
    private ImageView mImageView; 

    private static final int CAMERA_REQUEST = 1; 
    private static final int PICK_FROM_GALLERY = 2; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mTakePhoto = (Button) findViewById(R.id.take_photo); 
     mImageView = (ImageView) findViewById(R.id.imageview); 


     final String[] option = new String[] { "Take from Camera", "Select from Gallery" }; 

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, option); 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 

     builder.setTitle("Select Option"); 
     builder.setAdapter(adapter, new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
       // TODO Auto-generated method stub 
       Log.e("Selected Item", String.valueOf(which)); 
       if (which == 0) { 
        callCamera(); 
       } 
       if (which == 1) { 
        callGallery(); 
       } 

      } 
     }); 
     final AlertDialog dialog = builder.create(); 

     mTakePhoto.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       dialog.show(); 
      } 
     }); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 

     if (resultCode != RESULT_OK) 
      return; 

     switch (requestCode) { 
     case CAMERA_REQUEST: 

      setPic(); 

      break; 
     case PICK_FROM_GALLERY: 

      Bundle extras2 = data.getExtras(); 

      if (extras2 != null) { 
       Bitmap yourImage = extras2.getParcelable("data"); 
       // convert bitmap to byte 
       ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
       yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream); 
       byte imageInByte[] = stream.toByteArray(); 
       Log.e("output before conversion", imageInByte.toString()); 
       // Inserting Contacts 
       Log.d("Insert: ", "Inserting .."); 

       Intent i = new Intent(MainActivity.this, MainActivity.class); 

       startActivity(i); 

       finish(); 
      } 

      break; 
     } 
    } 

    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     Log.i(TAG, "onResume: " + this); 
    } 

    @Override 
    protected void onPause() { 
     // TODO Auto-generated method stub 
     super.onPause(); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     // TODO Auto-generated method stub 
     super.onConfigurationChanged(newConfig); 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     // TODO Auto-generated method stub 
     super.onSaveInstanceState(outState); 
     Log.i(TAG, "onSaveInstanceState"); 
    } 

    String mCurrentPhotoPath; 

    File photoFile = null; 

    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 
      if (photoFile != null) { 
       takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
       startActivityForResult(takePictureIntent, CAMERA_REQUEST); 
      } 
     } 
    } 

    private File createImageFile() throws IOException { 
     // Create an image file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     String imageFileName = "JPEG_" + timeStamp + "_"; 
     String storageDir = Environment.getExternalStorageDirectory() + "/uploads"; 
     File dir = new File(storageDir); 
     if (!dir.exists()) 
      dir.mkdir(); 

     File image = new File(storageDir + "/" + imageFileName + ".jpg"); 

     // Save a file: path for use with ACTION_VIEW intents 
     mCurrentPhotoPath = image.getAbsolutePath(); 
     Log.i(TAG, "photo path = " + mCurrentPhotoPath); 
     return image; 
    } 

    private void setPic() { 
     // Get the dimensions of the View 
     int targetW = mImageView.getWidth(); 
     int targetH = mImageView.getHeight(); 

     // Get the dimensions of the bitmap 
     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     bmOptions.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
     int photoW = bmOptions.outWidth; 
     int photoH = bmOptions.outHeight; 

     // Determine how much to scale down the image 
     int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 

     // Decode the image file into a Bitmap sized to fill the View 
     bmOptions.inJustDecodeBounds = false; 
     bmOptions.inSampleSize = scaleFactor << 1; 
     bmOptions.inPurgeable = true; 

     Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 

     Matrix mtx = new Matrix(); 
     mtx.postRotate(90); 
     // Rotating Bitmap 
     Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true); 

     mImageView.setImageBitmap(rotatedBMP); 

    } 

    public void callCamera() { 

     dispatchTakePictureIntent(); 

    } 

    public void callGallery() { 

     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     intent.putExtra("crop", "true"); 
     intent.putExtra("aspectX", 0); 
     intent.putExtra("aspectY", 0); 
     intent.putExtra("outputX", 200); 
     intent.putExtra("outputY", 150); 
     intent.putExtra("return-data", true); 
     startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY); 

    } 
} 

Спасибо, Marco

ответ

0

Потому что у вас есть этот код в вашей камере:

mImageView.setImageBitmap(rotatedBMP); 

Но вы не имеете его в галерее , Вы также должны установить растровое изображение в case PICK_FROM_GALLERY на onActivityResult.

Код должен выглядеть так:

if (extras2 != null) 
{ 
    Bitmap yourImage = extras2.getParcelable("data"); 
    //your other code 
    mImageView.setImageBitmap(yourImage); 
} 
+0

в моем случае PICK_FROM_GALLERY: я судимый положить setPic(); но он возвращает мне java.lang.nullPointerException. Конечно, мне нужен setImageBitmap (rotatedBMP), вы правы, но как лучше? Любое предложение? Thanks –

+0

спасибо! он работает .... когда закончите обратный отсчет, я получу этот ответ! Большое спасибо –

Смежные вопросы