2014-02-27 3 views
1

사진을 찍고 잘라내어 이미지 첨부 파일로 이메일을 보냅니다.Android : 사진을 찍은 다음 갤러리에서 선택해야하는 경우에만 바로 자르십시오.

다음은 코드의 흐름입니다. 사진 찍기>Gallery> 사진 첨부> 이메일 첨부 파일에서 방금 찍은 사진을 찾아 선택하십시오.

"방금 ​​갤러리에서 찍은 사진을 찾아서 선택하십시오."사진을 찍은 직후에 곧바로 자르기가 가능합니다.

내가 원하는 것을 할 수있는 의도가 있습니까?

나는이 자습서를 시도했다하지만 여전히 내가 복용하고 때 사용자가 갤러리에 가서 나는 사용자 정의보기를 가지고 나는 또한 언급해야한다 그들은 단지 http://www.londatiga.net/featured-articles/how-to-select-and-crop-image-on-android/

편집을 찍은 사진을 찾을 수 있습니다 그림이 너무 마음에 들지 않습니다. MediaStore.ACTION_IMAGE_CAPTURE

자르기를 실행하는 코드는 다음과 같습니다. 또한 갤러리를보고 방금 찍은 이미지를 선택할 수 있습니다.

 Intent crop_pic = new Intent(Intent.ACTION_PICK, uriTarget); // used to be ACTION_GET_CONTENT /ACTION_PICK 
      crop_pic.putExtra("crop", "true");       // this enables crop feature               
      //crop_pic.putExtra("aspectX", 200);       // this defines the aspect ration 
      //crop_pic.putExtra("aspectY", 150);      
      //crop_pic.putExtra("outputX", 500);       // this defines the output bitmap size 
      //crop_pic.putExtra("outputY", 500);  
      //crop_pic.putExtra("scale", true); 
    try { crop_pic.putExtra("return-data", false);      // true to return a Bitmap, false to directly save the cropped iamge        
      crop_pic.putExtra(MediaStore.EXTRA_OUTPUT, uriTarget);  // save output image in uri  
      //crop_pic.setDataAndType(uriTarget, "image/*");    // this will open all images in the Galery 
      startActivityForResult(crop_pic, EMAIL_PIC); 
      overridePendingTransition(R.anim.fadein, R.anim.fadeout);  
     } 
    catch (ActivityNotFoundException e) { 
      toast.showToastDialog(getApplicationContext(), e.toString());  
     } 
    LOGCAT.DEBUG(TAG, "Cropping Picture"); 

    } 

uri Target을 제공하면 자르기를 시작할 수 있다는 것을 모르는 의도가 있습니까?

public class DigitalSignature extends Activity implements SurfaceHolder.Callback{ 

      Camera camera; 
    SurfaceHolder surfaceHolder; 
      boolean previewing = false; 

       Uri uriTarget; 
      String[] recipients = new String[]{"[email protected]", "",}; 
     final int CROP_PIC = 1, EMAIL_PIC = 2, RETURN_ACTIVITY = 3, FINISH = 4, INDEX_GALLERY = 5; 

    final String TAG = "Digital Signature"; 

    ToastBuilder  toast = new ToastBuilder(this); 
    ProjectDebug  LOGCAT = new ProjectDebug(); 
ProgressDialogManager pDialog = new ProgressDialogManager(); 




@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

       DigitalSignature.this.requestWindowFeature(Window.FEATURE_NO_TITLE);   
       DigitalSignature.this.setContentView(R.layout.digitalsignature); 
       DigitalSignature.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 

       DigitalSignature.this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);    
       DigitalSignature.this.getWindow().setFormat(PixelFormat.TRANSLUCENT); // Used to be TRANSPARENT 



       SurfaceView  surfaceView = (SurfaceView)findViewById(R.id.camerapreview); 
           surfaceHolder = surfaceView.getHolder(); 
           surfaceHolder.addCallback(DigitalSignature.this); 
           surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

       LayoutInflater controlInflater = LayoutInflater.from(getApplicationContext()); 
       View   viewControl = controlInflater.inflate(R.layout.control, null); 
       LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 

       DigitalSignature.this.addContentView(viewControl, layoutParamsControl); // Applying Filters and Parameters 


       TextView  alignsig = (TextView)findViewById(R.id.alignsig); 
           alignsig.setText("Please take picture of the signature for" + "\n" + "Job Number " + DIGIJOB); 

       Button   buttonTakePicture = (Button)findViewById(R.id.takepicture); 
           buttonTakePicture.setOnClickListener(new Button.OnClickListener(){ 



     @Override 
     public void onClick(View arg0) {  
      LOGCAT.DEBUG(TAG, "Taking Picture"); 


        // Sets camera monochrome filter (Black and Whiite) 
        Camera.Parameters parameters = camera.getParameters();   
        parameters.setColorEffect(android.hardware.Camera.Parameters.EFFECT_MONO); 
        camera.setParameters(parameters);   
        camera.startPreview(); 


        // Initiate Camera Focus 
        camera.autoFocus(mAutoFocusCallback); 

        // Creates Directory to save image in gallery 
        uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues()); 

        //Notify the MediaScanner that a new file has been added and should be indexed so it shows up in the MediaStore. 
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
        intent.setData(uriTarget); 
        sendBroadcast(intent); 

        } 
      }); 
     } 






Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() { 

    @Override 
    public void onAutoFocus(boolean success, Camera camera) { 

     camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG); 
    } 
    }; 


ShutterCallback myShutterCallback = new ShutterCallback(){ 

    @Override 
    public void onShutter() { 

    }}; 


PictureCallback myPictureCallback_RAW = new PictureCallback(){ 

    @Override 
    public void onPictureTaken(byte[] arg0, Camera arg1) { 

    }}; 


PictureCallback myPictureCallback_JPG = new PictureCallback(){ 

    @Override 
    public void onPictureTaken(byte[] arg0, Camera arg1) { 
     //bmp = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);  

     cropPic(); 

    OutputStream imageFileOS; 
     try { 
       imageFileOS = getContentResolver().openOutputStream(uriTarget); 
       imageFileOS.write(arg0); 
       imageFileOS.flush(); 
       imageFileOS.close(); 

       toast.showToastDialog(getApplicationContext(), "Image saved: " + uriTarget.toString());        
      } 


     catch  (IOException e) { 
       toast.showToastDialog(getApplicationContext(), e.toString()); 
      }  

      // camera.startPreview(); // No need to start preview, we are saving 
      }};      // picture and no longer initiating camera 






    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    switch  (requestCode) { 

     case  CROP_PIC: 
        cropPic(); 
        LOGCAT.DEBUG(TAG, "cropPic Case");  
     break; 


     case  EMAIL_PIC: 
        emailPic(); 
        LOGCAT.DEBUG(TAG, "emailPic Case");   
     break;                 


     case  RETURN_ACTIVITY: 
        returnActivity(); 
        LOGCAT.DEBUG(TAG, "returnActivity Case");   
     break; 
      }  
    } 



    private void cropPic() { 


    Intent crop_pic = new Intent(Intent.ACTION_PICK, uriTarget); // used to be ACTION_GET_CONTENT /ACTION_PICK 
      crop_pic.putExtra("crop", "true");       // this enables crop feature               
      //crop_pic.putExtra("aspectX", 200);       // this defines the aspect ration 
      //crop_pic.putExtra("aspectY", 150);      
      //crop_pic.putExtra("outputX", 500);       // this defines the output bitmap size 
      //crop_pic.putExtra("outputY", 500);  
      //crop_pic.putExtra("scale", true); 
    try { crop_pic.putExtra("return-data", false);      // true to return a Bitmap, false to directly save the cropped iamge        
      crop_pic.putExtra(MediaStore.EXTRA_OUTPUT, uriTarget);  // save output image in uri  
      //crop_pic.setDataAndType(uriTarget, "image/*");    // this will open all images in the Galery 
      startActivityForResult(crop_pic, EMAIL_PIC); 
      overridePendingTransition(R.anim.fadein, R.anim.fadeout);  
     } 
    catch (ActivityNotFoundException e) { 
      toast.showToastDialog(getApplicationContext(), e.toString());  
     } 
    LOGCAT.DEBUG(TAG, "Cropping Picture"); 

    } 



    private void emailPic(){ 

    // new email_pic().execute();  

     GMailSender m = new GMailSender("[email protected]", "testtest"); 

     String[] toArr = { "[email protected]" }; 
     m.setTo(toArr); 
     m.setFrom("[email protected]"); 
     m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
     m.setBody("Email body."); 

     try { 
      m.addAttachment(getRealPathFromURI(uriTarget)); 

      if(m.send()) { 
      Toast.makeText(DigitalSignature.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
      } else { 
      Toast.makeText(DigitalSignature.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
      } 

     } catch(Exception e) { 
      //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
      Log.e("MailApp", "Could not send email", e); 
     } 


     // OLD METHOD OF SENDING EMAIL 
    /* Intent email_pic = new Intent(Intent.ACTION_SEND);  // Commence choose photo action   
     email_pic.putExtra(Intent.EXTRA_EMAIL, recipients);  // Inserts Digital Signature address automatically in recipient 
     email_pic.putExtra(Intent.EXTRA_SUBJECT, DIGIJOB);  // Inserts Track Number automatically in subject 
     email_pic.putExtra(Intent.EXTRA_STREAM, uriTarget);  // Attaches image to Gmail 
     email_pic.setType("image/jpeg");      // Converts image to jpeg 
     startActivityForResult(email_pic, RETURN_ACTIVITY); 
     overridePendingTransition(R.anim.fadein, R.anim.fadeout); */ 
     JOB = "job";           // Reset job variable from track no (1736) to "job" so                   
     LOGCAT.DEBUG(TAG, "Emailing Picture");      // when you go back into Jobs Activity, it can parse data. 

     returnActivity(); 

    } 






    private void returnActivity() { 
     Intent email_pic = new Intent(DigitalSignature.this, AgentPortalActivity.class); 
     startActivityForResult(email_pic, FINISH); 
     overridePendingTransition(R.anim.fadein, R.anim.fadeout);  
     LOGCAT.DEBUG(TAG, "Returning Activity"); 
    } 





    private String getRealPathFromURI(Uri uriTarget) { 

       String[] projection = { MediaStore.Images.Media.DATA }; 
       @SuppressWarnings("deprecation") 
       Cursor cursor = managedQuery(uriTarget, projection, null, null, null); 
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
            cursor.moveToFirst();  

      LOGCAT.DEBUG("getRealPathFromURI", cursor.getString(column_index)); 
      return cursor.getString(column_index); 

} 



@Override 
public void surfaceChanged(SurfaceHolder holder, int format, int width, 
     int height) { 


    if (previewing){ 
       camera.stopPreview(); 
       previewing = false; 
      } 

    if (camera != null){ 

    try { camera.setPreviewDisplay(surfaceHolder); 
      camera.startPreview(); 
      previewing = true; 
      } 

    catch (IOException e) { 
      toast.showToastDialog(getApplicationContext(), e.toString()); 
      } 
     } 
    } 




@Override 
public void surfaceCreated(SurfaceHolder holder) { 

    camera = Camera.open(); 
    //camera = Camera.open(0); 

    } 




@Override 
public void surfaceDestroyed(SurfaceHolder holder) { 

    camera.stopPreview(); 
    camera.release(); 
    camera = null; 
    previewing = false; 
} 
} 
+0

의견이 있으십니까? –

+0

** byte [] arg0 **에서 Jpeg 스트림을 처리 할 수있는'myPictureCallback.onPictureTaken()'이 있습니다. 'MediaStore가 없다.ACTION_IMAGE_CAPTURE'는 내가 이해하는 범위 내이므로, [@whizzle] (http://stackoverflow.com/users/1687169/whizzle)의 해결책은 적용 할 수 없습니다. –

+0

귀중한 의견을 보내 주셔서 감사합니다. Alex! 내가 어떻게 처리해야하는지에 대한 의견이 있으십니까? –

답변

1

당신은 단지 MediaStore.ACTION_IMAGE_CAPTURE 의도 액션을 사용해야합니다

여기에 전체 코드입니다. 그러면 카메라가 시작됩니다. 그리고 onActivityResult에서 방금 찍은 이미지를 얻을 수 있습니다. 이제자를 수 있고 다른 곳으로 보내실 수 있습니다. 아래는 그 예입니다.

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
File pics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
File cameraPhotoFile = new File(pics, System.currentTimeMillis()+".jpg"); 
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraPhotoFile)); 
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA); 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode != Activity.RESULT_OK) return; 
    if (requestCode == REQUEST_CODE_CAMERA) { 
     MediaScannerConnection.scanFile(this, 
       new String[]{cameraPhotoFile.getAbsolutePath()}, null, null); 

// do something with the image located at cameraPhotoFile 

이미지가 스캔 될 때까지 이미지가 갤러리에 표시되지 않기 때문에 MediaScannerConnection을 포함 시켰습니다. 원한다면 제거 할 수는 있지만, 나는 나타나기 위해 찍힌 이미지를 좋아합니다. 이제 비트 맵은 "cameraPhotoFile"에 있습니다. 원하는 파일을 사용하십시오.

Taking Photos Simply에 관한 Google의 문서도 여기에 있습니다. 그것은 꽤 똑바로 앞으로의

+0

그게 좋은 제안입니다. 그러나 내 코드에서 카메라를 호출 할 때 사용자 지정보기가 있습니다. MediaStore.ACTION_IMAGE_CAPTURE를 호출해도 사용자 정의보기를 계속 사용할 수 있습니까? –

+0

물론 할 수 있습니다 :) 실제로는 사용자 정의보기가있는 것처럼 들리지는 않습니다. 맞춤 카메라를 만들었던 것처럼 보입니다. 이 경우 갤러리를 처음 사용하는 이유는 무엇입니까? 이미지가 저장되는 것을 알 수 있습니다. BitmapFactory를 사용하여 이미지를 디코딩하고 갤러리를 우회하면됩니다. 그러나 카메라 앱을 사용하지 않는 한 맞춤형 카메라를 만들지 않는 것이 좋습니다. – whizzle

+0

답장을 보내 주셔서 감사합니다. 맞습니다. 사용자 정의보기가 아닌 맞춤 카메라가 있습니다. 나의 사과, 나는 차이가 있다는 것을 알지 못했다. 그래서, 당신이 제안하는 것은 public void onPictureTaken (byte [] arg0, Camera arg1)입니다. Bitmap bmp = BitmapFactory.decodeByteArray (arg0, 0, arg0.length);를 호출해야합니다. 바로 자르기를 시작합니까? 어떻게하면 의도를 잘라서 비트 맵 bmp로 보낼 수 있습니까? –

0

내가 생각할 수있는 가장 쉬운 솔루션입니다 : 새 그림의 내용 URI를 통해 얻을 것이다 onActivityResult를

  1. 를 호출 ACTION_IMAGE_CAPTURE 의도는 주식 카메라
  2. 와 함께 사진을 찍을 data.getData()
  3. 여기 vogella처럼 http://blog.vogella.com/2011/09/13/android-how-to-get-an-image-via-an-intent/ 그것을 수행 직접 새 그림

에 선택에 대한 필요를 InputStream를 열지 의지.

+0

이 솔루션에는 한 가지 질문이 있습니다. 카메라 작동 중에는 사용자 정의보기 설정이 있습니다. ACTION_IMAGE_CAPTURE 인 텐트를 호출해도 맞춤보기를 계속 사용할 수 있습니까? –

+0

사용자 정의보기가있는 경우 그림의 이진 데이터도 갖습니다. 그럼 당신의 질문을 이해하지 못합니다 –

+0

나는 그림의 데이터를 가지고 있지만, 내가 cropPic() 함수를 요청하면 방금 갤러리에서 가져온 그림을 선택해야합니다.그러나 내가 말하고자하는 것은, 만약 당신의 제안을 시도한다면, 제 카메라 레이아웃을 사용자 정의 할 수있는 능력을 잃어 버릴 것이라고 생각합니다. –

관련 문제