-1

ギャラリーとカメラから写真を撮る必要があります。カメラとギャラリーのオプションを尋ねるのと同じです。現在、画像をキャプチャして画像ビューに保存できます。ギャラリーとカメラから写真を撮るアンドロイド

、それはこれが私のコードでギャラリーから

を選ん後に再度カメラに戻って取っているギャラリーからアップロードする@BindView(R.id.selImage)ボタンselImage。 @Nullable @BindView(R.id.uProfileImage)ImageView uProfileImage;プライベートウリ fileUri;無効onActivityResult(int型requestCode、int型のresultCode、 テントデータ)

{

if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { 
     if (resultCode == RESULT_OK) { 
      // successfully captured the image 
      // display it in image view 
      previewCapturedImage(); 


     } else if (resultCode == RESULT_CANCELED) { 
      // user cancelled Image capture 
      Toast.makeText(getApplicationContext(), 
        "User cancelled image capture", Toast.LENGTH_SHORT) 
        .show(); 
     } else { 
      // failed to capture image 
      Toast.makeText(getApplicationContext(), 
        "Sorry! Failed to capture image", Toast.LENGTH_SHORT) 
        .show(); 
     } 
    } 
} 

ギャラリーから画像を追加する方法を私に提案し、自分のコードに格納してください保護

selImage.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      captureImage(); 
     } 
    }); 


private void captureImage() { 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); 

    Log.e("FileURI", "captureImage: "+fileUri); 

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 

    // start the image capture Intent 
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); 
} 



private void previewCapturedImage() { 
    try { 
     FileOutputStream out = null; 
     uProfileImage.setVisibility(View.VISIBLE); 

     // bimatp factory 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     // downsizing image as it throws OutOfMemory Exception for larger 
     // images 
     options.inSampleSize = 8; 

     final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), 
       options); 
     try { 

      out = new FileOutputStream(fileUri.getPath()); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , out); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     Log.e("Image", "previewCapturedImage: fileUri.getPath() "+fileUri.getPath()); 

     uProfileImage.setImageBitmap(getRoundedShape(bitmap)); 
    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 
} 

答えて

1

後あなたはこのコードを試すことができます。

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if(resultCode==RESULT_OK){ 
      if(requestCode==1){ 
       onSelectFromGalleryResult(data); 
      }else if(requestCode==2){ 
       onCaptureImageResult(data); 
      } 
     } 
    } 

//OnClick For Gallary Button 
public void pickFromGal(View view){ 
     Intent getIntent = new Intent(
       Intent.ACTION_PICK, 
       android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI); 
     getIntent.setType("image/*"); 
     startActivityForResult(getIntent, 1); 
    } 
//OnClick Camera Button 
    public void pickFromCam(View view){ 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(intent, 2); 
    } 



    private void onCaptureImageResult(Intent data) { 
     Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
     imageView.setImageBitmap(thumbnail); 

    } 
    private void onSelectFromGalleryResult(Intent data) { 
     Bitmap bm=null; 
     if (data != null) { 
      try { 
       Uri chosenImageUri = data.getData(); 
       bm = MediaStore.Images.Media.getBitmap(getContentResolver(), chosenImageUri);     
       imageView.setImageBitmap(bm); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
+0

これは私がカメラの画像を取得しているパスです:file:///storage/emulated/0/Pictures/PhysiotherapyProfileImage/Profile.jpgこれは私がギャラリーの画像を取得しているパスです:file:/// storage/emulated /0/Pictures/PhysiotherapyProfileImage/Profile.jpg ..カメラのようなギャラリーのファイルパスを取得する必要があります – Abhinay

+0

@Abhinay外部記憶装置にビットマップから新しいjpgファイルを作成できます。そしてその道を次のステップに使う。 ファイルf =新しいファイル(context.getCacheDir()、filename); f.createNewFile(); ; //ビットマップをバイト配列に変換する ビットマップビットマップ=あなたのビットマップ。 ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG、0/*はPNG * /、bosでは無視されます); byte [] bitmapdata = bos.toByteArray(); //ファイルにバイトを書き込む FileOutputStream fos = new FileOutputStream(f); fos.write(ビットマップデータ); fos.flush(); fos.close(); – mandeepsinghn

1
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      File filePhoto = new File(Environment.getExternalStorageDirectory(), "Pic.jpg"); 
      filePhoto.delete(); 
      imageUri = Uri.fromFile(filePhoto); 
      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
      startActivityForResult(intent, REQUEST_CODE); 
GALLARY

Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
           MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
         startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 

については

if (requestCode == this.REQUEST_CODE) { 
     Uri selectedImage = imageUri ; 
     this.getContentResolver().notifyChange(selectedImage, null); 
     ContentResolver cr = this.getContentResolver(); 
     Bitmap bitmap; 
     try { 
      bitmap = android.provider.MediaStore.Images.Media 
        .getBitmap(cr,imageUri); 
      imageView.setImageBitmap(bitmap); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Toast.makeText(this, "Camera is closed", Toast.LENGTH_SHORT).show(); 
     } 
    } else{ 

     try { 
      final Uri imageUri = data.getData(); 
      final InputStream imageStream = getContentResolver().openInputStream(imageUri); 
      bitmap = BitmapFactory.decodeStream(imageStream); 
      imageView.setImageBitmap(bitmap); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      // Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show(); 
     } 
    } 
+0

私はギャラリーから画像を取得することができていますが、それはカメラ – Abhinay

+0

@AbhinayのcheakのRequestCodeに再びリダイレクトされます...! –

0

ここから完全なソースコードをギャラリーから取得し、camaraの画像をキャプチャします。ここでは画像を切り抜くためのオプションも用意されています。ハッピーコーディングは、ボタンやイメージをクリックしてselectImageOption()メソッドを使用しても構いません。

private static final int CAMERA_CODE = 101, GALLERY_CODE = 201, CROPING_CODE = 301; 
    private Uri mImageCaptureUri; 
    private File outPutFile = null; 
    String encodedImage = ""; 
    String path = ""; 



    private void selectImageOption() { 
    final CharSequence[] items = {"Capture Photo", "Choose from Gallery", "Cancel"}; 

    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    builder.setTitle("Select Photo!"); 
    builder.setItems(items, new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int item) { 

      if (items[item].equals("Capture Photo")) { 

       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg"); 
       mImageCaptureUri = Uri.fromFile(f); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri); 
       startActivityForResult(intent, CAMERA_CODE); 

      } else if (items[item].equals("Choose from Gallery")) { 

       Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       startActivityForResult(i, GALLERY_CODE); 

      } else if (items[item].equals("Cancel")) { 
       dialog.dismiss(); 
      } 
     } 
    }); 
    builder.show(); 
} 
@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); // data = //file:///mnt/sdcard/temp.jpg 

    if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) { 

     mImageCaptureUri = data.getData(); // content://media/external/images/media/116 
     System.out.println("Gallery Image URI : " + mImageCaptureUri); 
     //CropingIMG(); 

     onSelectFromGalleryResult(data); 

    } else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) { 

     System.out.println("Camera Image URI : " + mImageCaptureUri); 
     CropingIMG(); 
     //onCaptureImageResult(data); 

    } else if (requestCode == CROPING_CODE && resultCode == RESULT_OK) { 

     try { 
      if (outPutFile.exists()) { 
       Bitmap photo = Common.decodeFile(outPutFile); 
       ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
       photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
       byte[] imageBytes = bytes.toByteArray(); 
       encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

       img_profile_personal_image.setImageBitmap(photo); 
       // img_profile_personal_image.setBackgroundColor(Color.TRANSPARENT); 
      } else { 
       Toast.makeText(context, "Error while save image", Toast.LENGTH_SHORT).show(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

    private void onCaptureImageResult(Intent data) { 
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 50, bytes); 
    byte[] imageBytes = bytes.toByteArray(); 
    encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

    File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpeg"); 
    FileOutputStream fo; 
    try { 
     destination.createNewFile(); 
     fo = new FileOutputStream(destination); 
     fo.write(bytes.toByteArray()); 
     fo.flush(); 
     fo.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    //Uri tempUri = getImageUri(mContext, thumbnail); 

    path = destination.getAbsolutePath(); 
    if (new File(path).exists()) { 
    //Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show(); 
    } 
    ivUserPic.setImageBitmap(thumbnail); 
} 

private void onSelectFromGalleryResult(Intent data) { 

    Bitmap bm = null; 
    if (data != null) { 
     try { 

      bm = Common.getCorrectlyOrientedImage(context, data.getData()); 

      Uri fileUri = data.getData(); 
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
       path = getPath(getActivity().getApplicationContext(), fileUri); 
      } 
      File file = new File(path); 

      if (file.exists()) {  
        Toast.makeText(mContext, "File " + file.getAbsolutePath(), Toast.LENGTH_LONG).show(); 
      } 
      Log.d("", "Video URI= " + fileUri); 

      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
      byte[] imageBytes = bytes.toByteArray(); 
      encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

      ivUserPic.setImageBitmap(bm); 
    } 
} 

    private void CropingIMG() { 
    final ArrayList<CropingOption> cropOptions = new ArrayList<CropingOption>(); 
    Intent intent = new Intent("com.android.camera.action.CROP"); 
    intent.setType("image/*"); 

    List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, 0); 
    int size = list.size(); 
    if (size == 0) { 
     Toast.makeText(context, "Cann't find image croping app", Toast.LENGTH_SHORT).show(); 
     return; 
    } else { 
     intent.setData(mImageCaptureUri); 
     intent.putExtra("outputX", 512); 
     intent.putExtra("outputY", 512); 
     intent.putExtra("aspectX", 1); 
     intent.putExtra("aspectY", 1); 
     intent.putExtra("scale", true); 

     //Create output file here 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile)); // "/mnt/sdcard/temp.jpg" 

     if (size == 1) { 
      Intent i = new Intent(intent); 
      ResolveInfo res = (ResolveInfo) list.get(0); 
      i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
      startActivityForResult(i, CROPING_CODE); 
     } else { 
      for (ResolveInfo res : list) { 
       final CropingOption co = new CropingOption(); 

       co.title = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo); 
       co.icon = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo); 
       co.appIntent = new Intent(intent); 
       co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
       cropOptions.add(co); 
      } 

      CropingOptionAdapter adapter = new CropingOptionAdapter(context, cropOptions); 
      AlertDialog.Builder builder = new AlertDialog.Builder(context); 
      builder.setTitle("Choose Croping App"); 
      builder.setCancelable(false); 
      builder.setAdapter(adapter, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int item) { 
        startActivityForResult(cropOptions.get(item).appIntent, CROPING_CODE); 
       } 
      }); 

      builder.setOnCancelListener(new DialogInterface.OnCancelListener() { 
       @Override 
       public void onCancel(DialogInterface dialog) { 

        if (mImageCaptureUri != null) { 
         context.getContentResolver().delete(mImageCaptureUri, null, null); 
         mImageCaptureUri = null; 
        } 
       } 
      }); 

      AlertDialog alert = builder.create(); 
      alert.show(); 
     } 
    } 
} 

Comman.java

public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException { 
    InputStream is = context.getContentResolver().openInputStream(photoUri); 
    BitmapFactory.Options dbo = new BitmapFactory.Options(); 
    dbo.inJustDecodeBounds = true; 
    BitmapFactory.decodeStream(is, null, dbo); 
    is.close(); 

    int rotatedWidth, rotatedHeight; 
    int orientation = getOrientation(context, photoUri); 

    if (orientation == 90 || orientation == 270) { 
     rotatedWidth = dbo.outHeight; 
     rotatedHeight = dbo.outWidth; 
    } else { 
     rotatedWidth = dbo.outWidth; 
     rotatedHeight = dbo.outHeight; 
    } 

    Bitmap srcBitmap; 
    int MAX_IMAGE_WIDTH = 1024; 
    int MAX_IMAGE_HEIGHT = 1024; 
    is = context.getContentResolver().openInputStream(photoUri); 
    if (rotatedWidth > MAX_IMAGE_WIDTH || rotatedHeight > MAX_IMAGE_HEIGHT) { 
     float widthRatio = ((float) rotatedWidth)/((float) MAX_IMAGE_WIDTH); 
     float heightRatio = ((float) rotatedHeight)/((float) MAX_IMAGE_HEIGHT); 
     float maxRatio = Math.max(widthRatio, heightRatio); 

     // Create the bitmap from file 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inSampleSize = (int) maxRatio; 
     srcBitmap = BitmapFactory.decodeStream(is, null, options); 
    } else { 
     srcBitmap = BitmapFactory.decodeStream(is); 
    } 
    is.close(); 

/* 
* if the orientation is not 0 (or -1, which means we don't know), we 
* have to do a rotation. 
*/ 
    if (orientation > 0) { 
     Matrix matrix = new Matrix(); 
     matrix.postRotate(orientation); 

     srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), 
       srcBitmap.getHeight(), matrix, true); 
    } 

    return srcBitmap; 
} 
関連する問題