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

3

2

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".

I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.

Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.

Everytime I am getting Java Socket TimeOut Exception.

Below is the code for my Camera Intent 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);
    } 
}
Vauntcourier answered 19/5, 2015 at 5:1 Comment(7)
Why you use ACTION_VIDEO_CAPTURE for image capture ? for image capturing have to use ACTION_IMAGE_CAPTURE with EXTRA_OUTPUT to location of image.Estate
i had video capturing in my early version of application !! I need to comment that code !!Vauntcourier
You posted way to much code. Please remove the most if it. Leave only the problematic code. And tell what the code should do. Remove also the uploading code. You can better post that as seperate post.Bibliopole
you have declared variables for private ImageButton insertImage; private ImageButton insertVideo; so why you are calling "ImageButton.OnclickListener " for video, You must write insertVideo.OnclickListener perhaps.Catgut
have you add the read and write permission to external storage.Maeve
@Chandra i did that but still images are corrupted ...!!Vauntcourier
you are deleting the file [ f.delete();] before the next one is created. delete it later after this statement outFile.close();Maeve
M
2

I simplified your code .keep reference of file path global

 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);

//your onactivityresult

@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();
            }
        } 

    }

}
Maeve answered 19/5, 2015 at 9:53 Comment(0)
S
0

Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.

Swampy answered 19/5, 2015 at 6:23 Comment(0)
T
0

After take the photo remember to use this:

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

to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in 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)));
            }
        });
Theomancy answered 19/5, 2015 at 10:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.