Android "TAKE PHOTO" - 单击的图像被保存为损坏的图像

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

我有一个按钮,它会打开一个对话框,要求用户选择 "Take Picture" 或 "Choose from gallery"。

我遇到问题 当用户 "Take photo" 图像被点击时,出于验证目的,我在 circularImage 视图中设置位图图像,但是当我去到图片的指定位置路径,图片不存在或图片已损坏。

此外,我正在尝试使用 android 中的 AsyncHttpClient 将图像上传到服务器,但无法成功完成。

每次我收到 Java 套接字超时异常。

下面是我的相机意图Activity

代码
public class AddAnUpdateActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        this.composeEditText = (EditText) findViewById(R.id.composeEditText);
        setContentView(R.layout.add_update);
        ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
        insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);        
        setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
        insertImage = (ImageButton) findViewById(R.id.insertImageButton);
        insertImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });
    }


    private void setBtnListenerOrDisable(ImageButton btn,
                                         Button.OnClickListener onClickListener,
                                         String intentName) {
        if (isIntentAvailable(this, intentName)) {
            btn.setOnClickListener(onClickListener);
        } else {
            btn.setClickable(false);
        }
    }

    private boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list =
                packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private void selectImage() {
        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options,new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if(options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @SuppressLint("Assert")
    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                Log.d("PhotoImage","file path:"+f);
                Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("Image.jpg")) {
                        Log.w("PhotoImage","enter in if block");
                        f = temp;
                        break;
                    }
                }
                try {
                    Log.w("PhotoImage","enter in else  block");
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);

                    ProfilePictureImage.setImageBitmap(bitmap);
                    if(bitmap!=null)
                    {
                        bitmap.recycle();
                        bitmap=null;
                    }
                    String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
                    Log.w("PhotoImage","path where the image is stored :"+path);
                    setFilePath(path);
                    f.delete();
                    OutputStream outFile;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");

                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                setFilePath(picturePath);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
                ProfilePictureImage.setImageBitmap(thumbnail);

            }
            else if(requestCode == 3){
                handleCameraVideo(data) ;
            }

        }

    }
    private void handleCameraVideo(Intent data) {
        VideoUri = data.getData();
        VideoView.setVideoURI(VideoUri);
        //mImageBitmap = null;
    }    }

    private void startActivityFeedActivity() {
        Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
        startActivity(i);
    } 
}

根据您的 Android 版本和设备,相机意图的实现方式有所不同。查看 https://github.com/ralfgehrer/AndroidCameraUtil。该代码在 100 多台设备上进行了测试。

我简化了你的代码。保留文件路径全局引用

 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
 globalpath =f.getAbsolutePath(); //String make it global
 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 startActivityForResult(intent, 1);

//你的活动结果

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File myfile = new File(globalpath);
            Bitmap bitmap;
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
                    bitmapOptions);

            ProfilePictureImage.setImageBitmap(bitmap);

            String path = android.os.Environment
                    .getExternalStorageDirectory()
                    + File.separator
                    + "Pictures" + File.separator + "Screenshots";
            OutputStream outFile;
            File file = new File(path, String.valueOf(System
                    .currentTimeMillis()) + ".jpg");
            try {
                outFile = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                outFile.flush();
                outFile.close();
                myfile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } 

    }

}

拍完照片记得用这个:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));

扫描您图库中的媒体文件。如果您不这样做,您的照片将在一段时间后出现。你可以在 onClick:

insertImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
            }
        });